Sql 根据另一列对一列进行计数,并在不同的表中显示计数
这是Sql 根据另一列对一列进行计数,并在不同的表中显示计数,sql,sql-server,pivot,Sql,Sql Server,Pivot,这是表A Wallet Type State ------------------------ 106 1 106 2 106 1 106 1 106 2 112 1 112 2 112 2 现在我需要一个表,它可以根据国家统计钱包类型 表B
表A
Wallet Type State
------------------------
106 1
106 2
106 1
106 1
106 2
112 1
112 2
112 2
现在我需要一个表,它可以根据国家统计钱包类型
表B
是这样的
State Distributor(106) Agent(112)
----------------------------------------
1 3 1
2 2 2
试试这个:
您可以使用Aggregate
函数来实现这一点
总和:
SELECT State
,SUM(CASE WHEN Wallet_Type = 106 THEN 1 ELSE 0 END) Distributor_106
,SUM(CASE WHEN Wallet_Type = 112 THEN 1 ELSE 0 END) Distributor_112
FROM Your_Table
WHERE Wallet_Type IN (106, 112)
GROUP BY State
SELECT State
,COUNT(CASE WHEN Wallet_Type = 106 THEN 1 END) Distributor_106
,COUNT(CASE WHEN Wallet_Type = 112 THEN 1 END) Distributor_112
FROM Your_Table
WHERE Wallet_Type IN (106, 112)
GROUP BY State
计数:
SELECT State
,SUM(CASE WHEN Wallet_Type = 106 THEN 1 ELSE 0 END) Distributor_106
,SUM(CASE WHEN Wallet_Type = 112 THEN 1 ELSE 0 END) Distributor_112
FROM Your_Table
WHERE Wallet_Type IN (106, 112)
GROUP BY State
SELECT State
,COUNT(CASE WHEN Wallet_Type = 106 THEN 1 END) Distributor_106
,COUNT(CASE WHEN Wallet_Type = 112 THEN 1 END) Distributor_112
FROM Your_Table
WHERE Wallet_Type IN (106, 112)
GROUP BY State
对于这种情况,可以使用透视表
declare @t1 table (wallet_type int, state int)
insert into @t1
values (106, 1),
(106 , 2 ),
(106 , 1 ),
(106 , 1 ),
(106 , 2 ),
(112 , 1 ),
(112 , 2 ),
(112 , 2 )
--select * from @t1
select *
from
(
select state, wallet_type, count(wallet_type) 'count' from @t1
group by state, wallet_type
) src
pivot
(
sum(count)
for wallet_type in ([106], [112])
) piv;
在线演示:试试这个。。。(动态枢轴)
输出
+-------+-----+-----+
| State | 106 | 112 |
+-------+-----+-----+
| 1 | 3 | 1 |
| 2 | 2 | 2 |
+-------+-----+-----+
也可以使用SQL server中的PIVOT关键字解决这些类型的问题。 了解有关PIVOT的更多信息 使用PIVOT的查询应该如下
select
[state],
[Distributor(106)]=[106],
[Agent(112)]=[112]
from
(
select
[state],
[cstate]=state, -- created duplicate as this will be consumed in count operation and will not be available as output column later
[Wallet Type]
from tableA
) src
pivot
(
count(cstate) for [Wallet Type] in ([106],[112])
)p
首先,您需要声明一个cols变量,该变量将为您提供稍后在查询中使用的所有不同钱包类型:
DECLARE @cols AS NVARCHAR(max) =
Stuff((SELECT DISTINCT ', ' + Convert(nvarchar, WalletType)
FROM [IHC].[dbo].[TABLENAMEHERE]
FOR XML PATH ('')), 1, 2, '')
它所做的是,它得到所有不同的逗号分隔的钱包类型。因为XML路径提供XML格式的数据,所以我们可以使用它
然后按照一些人的建议使用PIVOT操作符。在这里:
select *
from
(
select [state], [WalletType], count([WalletType]) as count FROM [IHC].[dbo].[TABLENAMEHERE]
group by [state], [WalletType]
) SourceTable
pivot
(
sum(count)
for [WalletType] in (@cols)
) piv;
此查询的第一部分为您提供按州和钱包类型分组的州、WalletType、“钱包计数”类型,或者说断开的w.r.t州和钱包类型
像这样:
州钱包类型计数
11064 2 106 2 11121 21122
现在,在PIVOT函数中使用此“钱包计数”作为Count,以获取钱包类型的w.r.t计数之和,因此它对w.r.t WalletType计数求和,并给出最终结果
确保在动态查询中使用它。假设106和112之间没有第三个。