I have a table that looks like below. The values are number of contracts each customer have each month.
CustomerNo | CustomerType | 201901 | 201902 | 201903 |
-----------+---------------+----------+----------+----------|
1 | Private | 1 | 0 | 0 |
2 | Private | 0 | 1 | 1 |
3 | Enterprise | 1 | 1 | 0 |
4 | Enterprise | 1 | 1 | 1 |
I want to unpivot the YearMonth columns and group by CustomerType, YearMonth so the table looks like this:
CustomerType | YearMonth | Contracts |
-------------+-----------+-----------|
Private | 201901 | 1 |
Enterprise | 201901 | 2 |
Private | 201902 | 1 |
Enterprise | 201902 | 2 |
Private | 201903 | 1 |
Enterprise | 201903 | 1 |
How
I would just use apply
:
select v.*
from t cross apply
(values (t.customerType, 201901, t.[201901]),
(t.customerType, 201902, t.[201902]),
(t.customerType, 201903, t.[201903])
) v(CustomerType, YearMonth, Contracts)
where Contracts > 0;
I much prefer apply
because this is a good introduction to lateral joins , very handy functionality in SQL databases.
The alternative of unpivot
is bespoke syntax and it only does one thing (and in my opinion, not very elegantly either).
For MS SQL Server:
SELECT CustomerType, YearMonth, SUM(Contracts) Contracts
FROM (
SELECT CustomerNo, CustomerType, [201901], [201902], [201903]
FROM Customers
) pvt
UNPIVOT(Contracts FOR YearMonth IN([201901], [201902], [201903])) unpvt
GROUP BY CustomerType, YearMonth;
Result:
CustomerType YearMonth Contracts
Enterprise 201901 2
Private 201901 1
Enterprise 201902 2
Private 201902 1
Enterprise 201903 1
Private 201903 1
Link to db<>fiddle
MSDN documentation: UNPIVOT
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.