在SQL Server中通过SQL查询编写多个组

时间:2019-06-18 16:36:20

标签: sql sql-server

我有一个表User,其中有UserId,Country和State列。 用户表数据如下

-------------------------------
| UserId |  Country |  State  |
--------------------------------
| AAA     |  US      |  AR     |
| BBB     |  GB      |  LN     |
| BBB     |  MX      |  MC     |
| AAA     |  MX      |  CH     |
| CCC     |  GB      |  LE     |
| CCC     |          |  IL     |
--------------------------------

预期结果如下,

---------------------------------------------------------------------
UserId   totalcountry US  MX  GB TotalState   AR LN  MC  CH  LE  IL
----------------------------------------------------------------------
AAA      2             1  1   0    2          1  0   0   1   0   0
BBB      2             0  1   1    2             1   1   0   0   0
CCC      1             0  0   1    0          0  0   0   0   1   1
-----------------------------------------------------------------------

1 个答案:

答案 0 :(得分:0)

您可以使用PIVIOT来获得所需的结果,如下所示-

SELECT [User ID],

SUM([US])+SUM([GB])+SUM([MX]) [total country],
SUM([US]) US,SUM([GB]) GB, SUM([MX]) MX,

SUM([AR])+SUM([LN])+SUM([MC])+SUM([CH])+SUM([LE])+SUM([IL]) [Total State],
SUM([AR]) AR, SUM([LN]) LN, SUM([MC]) MC, SUM([CH]) CH, SUM([LE]) LE, SUM([IL]) IL

FROM
(
    SELECT [User id],Country,State
    FROM your_table
) AS P
PIVOT
(
    COUNT(Country)
    FOR Country IN ([US],[GB],[MX])
) PVT

PIVOT(
    COUNT(State)
    FOR State IN ([AR],[LN],[MC],[CH],[LE],[IL])
) PVT2
GROUP BY [User ID]