I have a data table that looks like this:
StreamID | PeriodID | MIN | MAX |
---|---|---|---|
STR_01 | 1 | 0 | 9 |
STR_01 | 2 | 0 | 7 |
STR_01 | 3 | 4 | 9 |
STR_02 | 1 | 2 | 5 |
STR_02 | 2 | 1 | 8 |
STR_02 | 3 | 0 | 6 |
I'd like to build a pivot table that looks like this:
StreamID | MIN1 | MIN2 | MIN3 | MAX1 | MAX2 | MAX3 |
---|---|---|---|---|---|---|
STR_01 | 0 | 0 | 4 | 9 | 7 | 9 |
STR_02 | 2 | 1 | 0 | 5 | 8 | 6 |
How can I do that using SQL language? Is it possible to pivot directly using more than one field value or do I need to unpivot the original table and create joins with the pivot tables? Is it possible to join pivot tables? I've tried to unpivot data like this:
StreamID | PeriodID | Parameter | Value |
---|---|---|---|
STR_01 | 1 | MIN | 0 |
STR_01 | 1 | MAX | 9 |
STR_01 | 2 | MIN | 0 |
STR_01 | 2 | MAX | 7 |
STR_01 | 3 | MIN | 4 |
STR_01 | 3 | MAX | 9 |
lIf classes are fixed, and the number of periods are dynamic, the following Query produces your desired result:
TRANSFORM First(MinMax)
SELECT StreamID
FROM
( SELECT StreamID, "MIN" & PeriodID AS Piv, MIN AS MinMax
FROM Tabla1
UNION ALL
SELECT StreamID, "MAX" & PeriodID AS Piv, MAX AS MinMax
FROM Tabla1
)
GROUP BY StreamID
PIVOT Piv
IN ("MIN1", "MIN2", "MIN3", "MAX1", "MAX2", "MAX3") ;
In case the number of periods is also dynamic, you just need to remove the "IN" clause, and it will still work, although the order of columns will be determined by the alfanumeric ordering of column names. In this specific case, the "MAX" columns will appear before the "MIN" columns.
You may also want to check the five example queries "F_Transform_..." from the database downloadable from LightningGuide.net . The Query code I provide above can be generalized to a case with more classes (MIN, MAX, MID, ...) as long as the classes are known in advance.
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.