SQL Server 使用游标进行查询
下面的查询计算加利福尼亚州 2009 财年与 2010 财年之间的产品百分比。我被分配计算剩余的状态(请参阅状态表)。 SQL Server中有没有一种方法可以计算各州的百分比?我目前一次手动计算每个状态。
(请注意,由于数据完整性,我必须单独使用状态表。我在想游标是否可以做到这一点,但我还没有做到这一点。)
DECLARE @LOCATION VARCHAR(2)
SET @state = 'CA'
SELECT NUMBER1/CAST(NUMBER2 as FLOAT) as PERCENTAGE
FROM
(
SELECT COUNT (PRODUCT) as NUMBER1
FROM SOMETABLE1
WHERE LOCATION = @state
AND DATE >='10/1/2008'
AND DATE <' 10/1/2009'
)X,
(
SELECT COUNT (PRODUCT) as NUMBER2
FROM SOMETABLE2
WHERE LOCATION = @state
AND DATE >='10/1/2009'
AND DATE <' 10/1/2010'
)Y
PERCENTAGE
1.400742
SELECT state
FROM STATES
STATE
CA
AZ
TX
NV
NM
UT
OR
CO
WA
The query below calculates the percentage of a product between FY2009 vs. FY2010 for California. I am assigned to calculate the remaining states (Please see STATES table). Is there a way in SQL Server that could calculate the states percentages? I am currently manually calculate each state at a time.
(Please note, I must use the states table separately due to data integrity. I was thinking if a cursor would do it, but I am not there yet.)
DECLARE @LOCATION VARCHAR(2)
SET @state = 'CA'
SELECT NUMBER1/CAST(NUMBER2 as FLOAT) as PERCENTAGE
FROM
(
SELECT COUNT (PRODUCT) as NUMBER1
FROM SOMETABLE1
WHERE LOCATION = @state
AND DATE >='10/1/2008'
AND DATE <' 10/1/2009'
)X,
(
SELECT COUNT (PRODUCT) as NUMBER2
FROM SOMETABLE2
WHERE LOCATION = @state
AND DATE >='10/1/2009'
AND DATE <' 10/1/2010'
)Y
PERCENTAGE
1.400742
SELECT state
FROM STATES
STATE
CA
AZ
TX
NV
NM
UT
OR
CO
WA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以加入 STATES 表。沿着这些思路:
You can join on the STATES table. Something along these lines: