SQL 查询使用 MERGE 或其他不带数据透视的更快方法对列进行数据透视 table
SQL query to pivot a column using MERGE or another faster ways without pivot table
我有以下 table:
paymentgateway status
-------------- --------
1 1
2 2
3 1
2 3
2 3
. .
. .
. .
我正在尝试编写一个 SQL 查询以提供以下结果:
paymentgetways status1 status2 status3
-------------- ------ ------- --------
1 1 0 1
2 0 1 2
3 1 0 0
.
.
.
如何修改我的查询以给出正确的表示?我不想用 case when,谢谢
这里是static pivot query
,根据需要改成dynamic
。参考 Dynamic PIVOT in Sql Server
DECLARE @Test AS TABLE(paymentgateway int, status int)
insert into @Test VALUES(1,1)
insert into @Test VALUES(2,2)
insert into @Test VALUES(3,1)
insert into @Test VALUES(2,3)
insert into @Test VALUES(2,3)
SELECT paymentgateway, [1] AS status1, [2] AS status2, [3] AS status3 FROm @Test
PIVOT (COUNT(Status) FOR Status IN ([1], [2], [3])) AS A
我有以下 table:
paymentgateway status
-------------- --------
1 1
2 2
3 1
2 3
2 3
. .
. .
. .
我正在尝试编写一个 SQL 查询以提供以下结果:
paymentgetways status1 status2 status3
-------------- ------ ------- --------
1 1 0 1
2 0 1 2
3 1 0 0
.
.
.
如何修改我的查询以给出正确的表示?我不想用 case when,谢谢
这里是static pivot query
,根据需要改成dynamic
。参考 Dynamic PIVOT in Sql Server
DECLARE @Test AS TABLE(paymentgateway int, status int)
insert into @Test VALUES(1,1)
insert into @Test VALUES(2,2)
insert into @Test VALUES(3,1)
insert into @Test VALUES(2,3)
insert into @Test VALUES(2,3)
SELECT paymentgateway, [1] AS status1, [2] AS status2, [3] AS status3 FROm @Test
PIVOT (COUNT(Status) FOR Status IN ([1], [2], [3])) AS A