按年份对数据进行分类

时间:2013-12-26 03:33:44

标签: sql sql-server tsql sql-server-2012 pivot

我有一张表,其中包含有关客户和代理商的信息。我希望按月分类。

澄清:我想知道一年中有多少客户在不同代理商下注册,与下图相同:

enter image description here


2 个答案:

答案 0 :(得分:4)

您可以使用PIVOT

SELECT AGENT_CODE, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]
FROM 
(SELECT CUSTOMER_ID, AGENT_CODE, MONTH(DATE) as m
FROM Test) t
PIVOT
(
COUNT (CUSTOMER_ID)
FOR m IN
( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )
) AS pvt;

返回

AGENT_CODE  1   2   3   4   5   6   7   8   9   10  11  12
100         1   0   0   0   2   1   1   0   1   0   0   3
101         0   0   2   0   0   0   1   0   0   1   1   0
102         0   0   0   0   0   0   1   1   0   0   0   0
103         0   0   0   1   0   0   0   0   0   0   0   0

添加列别名以获取JANFEB等,而不是数字作为列标题。

工作演示:http://sqlfiddle.com/#!6/673cb/7

答案 1 :(得分:1)

SELECT * FROM(

SELECT year(DATE)as [year],left(datename(month,DATE),3)as [month],AGENT_CODE as cnt FROM yourTable

)s 枢 (     COUNT(AGENT_CODE)     FOR [月] IN(jan,feb,mar,apr,     may,jun,jul,aug,sep,oct,nov,dec) )AS pivot