SQL with与group by

时间:2013-07-29 03:17:26

标签: sql group-by

以下是列表条目:

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中吗?

谢谢, 替补

1 个答案:

答案 0 :(得分: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