SQL PIVOT可以做这样的转换吗?

时间:2016-08-02 06:30:39

标签: sql sql-server tsql pivot

我的数据看起来像

+-------+-------+-------+------+
| Group | Count | Month | Year |
+-------+-------+-------+------+
| A     |   102 | Jan   | 2015 |
| B     |    20 | Jan   | 2016 |
| C     |    30 | Feb   | 2015 |
| A     |    10 | Jan   | 2016 |
| C     |    20 | Feb   | 2016 |
+-------+-------+-------+------+

我希望输出像

+-------+-------+------+-------+
| Group | Month | 2015 |  2016 |
+-------+-------+------+-------+
| A     | Jan   |   102|    10 |
| B     | Jan   |   20 |     0 |
| C     | Feb   |   30 |    20 |
+-------+-------+------+-------+

我尝试使用PIVOT,但我不确定它是否会显示我想要的结果。

以下查询是我的不良尝试(没有工作) -

SELECT 'Total' AS Total, 
    [2015], [2016]
    FROM
    (SELECT DATENAME(YEAR,[mydate]) as Y, Datename(month,[mydate]) as M
     FROM incidents) AS SourceTable
    PIVOT
    (
     count(DATENAME(YEAR,[mydate]))
     FOR DATENAME(YEAR,[mydate]) IN (2015,2016)
    ) AS PivotTable;

我的日期列采用此格式2016-01-20 03:00:11.000。我使用MONTH()DATENAME函数来提取月份编号和名称。

2 个答案:

答案 0 :(得分:6)

我认为这就是你所需要的:

WITH Src AS
(
    SELECT * FROM (VALUES
    ('A',102, 'Jan', 2015),
    ('B', 20, 'Jan', 2016),
    ('C', 30, 'Feb', 2015),
    ('A', 10, 'Jan', 2016),
    ('C', 20, 'Feb', 2016)) T([Group], Count, Month, Year)
)
SELECT [Group],Month,ISNULL([2015],0) [2015],ISNULL([2016],0) [2016] FROM Src
PIVOT
(SUM(Count) FOR Year IN ([2015], [2016])) AS Pvt
ORDER BY [Group],Month

答案 1 :(得分:3)

实际上不需要实际的pivot操作。

select
    "Group", "Month",
    case when "Year" = 2015 then sum("Count") end as "2015",
    case when "Year" = 2016 then sum("Count") end as "2016"
from incidents
group by "Group", "Month"

sum()聚合只是这个样本数据的虚函数。它可以很容易min()max()avg()甚至。