0

以下是列表条目:

GROUPNUMBER|COUNTRY|COUNT|AMOUNT
BD2        |US     |4    |2.00
BD2        |US     |10   |8.00
BD2        |CANADA |12   |10.00
BD5        |UK     |2    |1.00
BD5        |US     |6    |4.00
BD5        |UK     |8    |6.00

需要的结果输出:

GROUPNUMBER|US_COUNT|US_AMOUNT|NON_US_COUNT|NON_US_AMOUNT
BD2        |14      |10.00    |12          |10.00
BD5        |6       |4.00     |10          |7.00

需要将计数和金额用 US 和 NON_US 分开,并按 GroupNumber 字段分组。这在 MS SQL 中可能吗?

谢谢,潜艇

4

1 回答 1

1

应该可以通过以下CASE声明:

SELECT
    GROUPNUMBER,
    SUM(CASE WHEN COUNTRY = 'US' THEN [COUNT] ELSE 0 END) AS US_COUNT,
    SUM(CASE WHEN COUNTRY = 'US' THEN AMOUNT ELSE 0 END) AS US_AMOUNT,
    SUM(CASE WHEN COUNTRY != 'US' THEN [COUNT] ELSE 0 END) AS NON_US_COUNT,
    SUM(CASE WHEN COUNTRY != 'US' THEN AMOUNT ELSE 0 END) AS NON_US_AMOUNT
FROM theTable
GROUP BY GROUPNUMBER

SqlFiddle

于 2013-07-29T03:24:04.413 回答