我已将记录数据存储在SQL Server上,我想获得一个简单的查询来获取每种记录类型的总数。我有一个具有以下模式的表:
Id | Type | ID_Type |
-----------------------
1 | Bags | B1 |
2 | Shoes | S1 |
3 | Shoes | S1 |
4 | Bags | B1 |
..
我的记录的Type
是动态的,如果用户添加了Shirts
之类的新Type并创建了新记录,我的查询也应该得到Shirts
的总和,这就像一个类别。这是我的示例数据:
Id | Type | ID_Type |
------------------------
1 | Bags | B1 |
2 | Shoes | S1 |
3 | Shoes | S1 |
4 | Bags | B1 |
5 | Shirts | S2 |
6 | Shirts | S2 |
7 | Shirts | S2 |
..
以下是我希望获得的记录总数的结果:
Bags | Shoes | Shirts | Total |
-------------------------------
2 | 2 | 3 | 7
答案 0 :(得分:1)
您可以通过这种方式处理case语句。
with cte as (
Select 1 as ID, 'Bags' as [Type] union all
Select 2 as ID, 'Shoes' as [Type] union all
Select 3 as ID, 'Shoes' as [Type] union all
Select 4 as ID, 'Bags' as [Type] union all
Select 5 as ID, 'Shirts' as [Type] union all
Select 6 as ID, 'Shirts' as [Type] union all
Select 7 as ID, 'Shirts' as [Type] )
select count(case when [type] ='Bags' then ID end) Bags, count(case when [type]
='Shoes' then ID end) Shoes ,
count(case when [type] ='Shirts' then ID end) Shirts, count(1) total from cte;
输出:
Bags Shoes Shirts total
2 2 3 7
使用动态SQL方法:
如果列是动态的,则可以通过这种方式获得结果。
测试数据:
-- drop table #temp
Select 1 as ID, 'Bags' as [Type] into #temp union all
Select 2 as ID, 'Shoes' as [Type] union all
Select 3 as ID, 'Shoes' as [Type] union all
Select 4 as ID, 'Bags' as [Type] union all
Select 5 as ID, 'Shirts' as [Type] union all
Select 6 as ID, 'Shirts' as [Type] union all
Select 7 as ID, 'Shirts' as [Type]
--drop table #temp1
select *, ROW_NUMBER() over (partition by [Type] order by ID) Rownum
into #temp1 from #temp
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Type)
FROM #temp c
FOR XML PATH(''))
,1,1,'')
set @query = 'SELECT '+@cols+' ,total from
(
select Type, ID, total
from #temp1 t
join (select count(1) total from #temp1) t1 on 1= 1
) x
pivot
(
count(ID)
for Type in (' + @cols + ')
) p '
Exec sp_executesql @query
Output:
Bags Shirts Shoes total
2 3 2 7
答案 1 :(得分:1)
您可以创建动态PIVOT
,如下所示。要生成Total
列,您只需在WITH ROLLUP
GROUP BY
DECLARE @cols AS NVARCHAR(max) = Stuff((SELECT DISTINCT ', ' + Quotename([Type])
FROM [YourTableName]
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ',[Total]';
EXECUTE('SELECT * FROM (select ISNULL(type, ''total'') as Type,Count(*) n
from [YourTableName] GROUP BY [Type] WITH ROLLUP) s
PIVOT (max(n) FOR [Type] IN ('+@cols+') ) pvt')
输出
+------+--------+-------+-------+
| Bags | Shirts | Shoes | Total |
+------+--------+-------+-------+
| 2 | 3 | 2 | 7 |
+------+--------+-------+-------+