SQL Server 使用游标进行查询

发布于 2024-10-08 16:40:46 字数 692 浏览 2 评论 0原文

下面的查询计算加利福尼亚州 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

漫雪独思 2024-10-15 16:40:46

您可以加入 STATES 表。沿着这些思路:

SELECT X.STATE, X.NUMBER1/CAST(Y.NUMBER2 as FLOAT) as PERCENTAGE
FROM
(
    SELECT S.STATE, COUNT(*) as NUMBER1
    FROM SOMETABLE1 AS S1
    INNER JOIN STATES AS S ON S1.LOCATION = S.STATE
    AND S1.DATE >='10/1/2008'
    AND S1.DATE < '10/1/2009'
    GROUP BY S.STATE
)X,

(
    SELECT S.STATE, COUNT (*) as NUMBER2
    FROM SOMETABLE2 AS S2
    INNER JOIN STATES AS S ON S2.LOCATION = S.STATE
    AND S2.DATE >='10/1/2009'
    AND S2.DATE < '10/1/2010'
    GROUP BY S.STATE
)Y
WHERE X.STATE = Y.STATE

You can join on the STATES table. Something along these lines:

SELECT X.STATE, X.NUMBER1/CAST(Y.NUMBER2 as FLOAT) as PERCENTAGE
FROM
(
    SELECT S.STATE, COUNT(*) as NUMBER1
    FROM SOMETABLE1 AS S1
    INNER JOIN STATES AS S ON S1.LOCATION = S.STATE
    AND S1.DATE >='10/1/2008'
    AND S1.DATE < '10/1/2009'
    GROUP BY S.STATE
)X,

(
    SELECT S.STATE, COUNT (*) as NUMBER2
    FROM SOMETABLE2 AS S2
    INNER JOIN STATES AS S ON S2.LOCATION = S.STATE
    AND S2.DATE >='10/1/2009'
    AND S2.DATE < '10/1/2010'
    GROUP BY S.STATE
)Y
WHERE X.STATE = Y.STATE
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文