首页 > 解决方案 > 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

谢谢

标签: sqlsql-server

解决方案


尝试将此作为基本查询,然后根据此查询结果编写一个数据透视查询,如演示链接中所示。

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演示。


推荐阅读