sql - SQL 组计数
问题描述
我有一张这样的桌子
Date County Location
2020-01-01 abc west
2020-01-02 abc north
2020-02-01 xzy west
2020-02-02 xzy east
2020-02-03 xyz east
我们可以分组和计数,这样它就可以变成
County jan feb
abc 2
xyz 3
Location jan feb
west 1
north 1
west 1
east 2
谢谢
解决方案
尝试将此作为基本查询,然后根据此查询结果编写一个数据透视查询,如演示链接中所示。
FROM - 使用 PIVOT 和 UNPIVOT供您参考。
Select country
, FORMAT([date], 'MMMM') as Month
, count(*) as Tot
from YourTable
group by country, FORMAT([date], 'MMMM')
透视查询需要一个聚合函数。这是完整的查询。
create table YourTable
([Date] Date
, Country varchar(20)
, Location varchar(20))
insert into YourTable values
('2020-01-01', 'abc', 'west'),
('2020-01-02', 'abc', 'north'),
('2020-02-01', 'xzy', 'west'),
('2020-02-02', 'xzy', 'east'),
('2020-02-03', 'xyz', 'east')
Select * into #temp from(
Select country
, FORMAT([date], 'MMMM') as Month
, count(*) as Tot
from YourTable
group by country, FORMAT([date], 'MMMM')
)a
--Select * from #temp
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Month)
FROM #temp c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT country, ' + @cols + ' from
(
select Country
, Month
, Tot
from #temp
) x
pivot
(
max(Tot)
for Month in (' + @cols + ')
) p '
execute(@query)
现场db<>fiddle演示。
推荐阅读
- r - 如何根据另一列字符串提取部分字符串?
- java - Selenium WebDriver (JAVA) - 流畅的等待似乎不起作用
- javascript - 硬绑定与调用
- regex - 正则表达式匹配模式之间的内容与相同模式Python环境中的条件
- bash - How would i get a process pid which is running in a bash script and know when its done
- linkedin - 如何成为领英认可的开发者使用领英的 Connections API?
- typescript - Match "any" but not array
- wordpress - Create subdirectory on Google Cloud Wordpress Installation on Virtual Machine
- php - 我想在我的项目中的views文件夹中的一个文件中引用其中一个数据库表
- python-3.x - Splitting a dataframe (csv)