Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can SQL PIVOT do such transformation?

My data looks like

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

I want the output like

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

I tried using PIVOT but I'm not sure if it will show the outcome as I want.

The below query is a poor attempt by me (doesn't work)-

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;

My date column is in this format 2016-01-20 03:00:11.000. I use MONTH() and DATENAME function to extract month number and name.

like image 417
Pirate X Avatar asked Aug 02 '16 06:08

Pirate X


People also ask

What is PIVOT transformation?

A pivot transformation turns multiple rows of data into one, denormalizing a data set into a more compact version by rotating the input data on a column value. For example, a normalized sales report that includes store names, dates and sales amounts has several rows for each store.

Can we use PIVOT in CTE?

Creating a Temporary Data Set In order to pivot the data we need to create some form of temporary data set which we can pivot. You can use Common Table Expressions (CTE), Derived Tables or Temporary Tables to do this.

What does SQL PIVOT do?

PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output. And PIVOT runs aggregations where they're required on any remaining column values that are wanted in the final output.


1 Answers

I think this is what you need:

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
like image 56
Paweł Dyl Avatar answered Oct 17 '22 22:10

Paweł Dyl