Skip to content

Commit

Permalink
Support PIVOT / UNPIVOT
Browse files Browse the repository at this point in the history
  • Loading branch information
ohaibbq committed Mar 28, 2024
1 parent 745096f commit d44cbf9
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,8 @@ A list of ZetaSQL ( Google Standard SQL ) specifications and features supported
- [ ] Explicit and implicit UNNEST
- [ ] UNNEST and NULLs
- [ ] UNNEST and WITH OFFSET
- [ ] PIVOT operator
- [ ] UNPIVOT operator
- [x] PIVOT operator
- [x] UNPIVOT operator
- [ ] TABLESAMPLE operator
- [x] JOIN operation
- [x] INNER JOIN
Expand Down
2 changes: 2 additions & 0 deletions internal/analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ func newAnalyzerOptions() *zetasql.AnalyzerOptions {
zetasql.FeatureV13ExtendedGeographyParsers,
zetasql.FeatureTemplateFunctions,
zetasql.FeatureV11WithOnSubquery,
zetasql.FeatureV13Pivot,
zetasql.FeatureV13Unpivot,
})
langOpt.SetSupportedStatementKinds([]ast.Kind{
ast.BeginStmt,
Expand Down
45 changes: 45 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3961,6 +3961,51 @@ WITH example AS (
query: `SELECT DATE_ADD('2023-01-29', INTERVAL 1 MONTH)`,
expectedRows: [][]interface{}{{"2023-02-28"}},
},
{
name: "PIVOT",
query: `
WITH produce AS (
SELECT 'Kale' AS product, 51 AS sales, 'Q1' AS quarter, 2020 AS year UNION ALL
SELECT 'Kale', 23, 'Q2', 2020 UNION ALL
SELECT 'Kale', 45, 'Q3', 2020 UNION ALL
SELECT 'Kale', 3, 'Q4', 2020 UNION ALL
SELECT 'Kale', 70, 'Q1', 2021 UNION ALL
SELECT 'Kale', 85, 'Q2', 2021 UNION ALL
SELECT 'Apple', 77, 'Q1', 2020 UNION ALL
SELECT 'Apple', 0, 'Q2', 2020 UNION ALL
SELECT 'Apple', 1, 'Q1', 2021
)
SELECT * FROM
Produce
PIVOT(SUM(sales) FOR quarter IN ('Q1', 'Q2', 'Q3', 'Q4'))
`,
expectedRows: [][]interface{}{
{"Apple", int64(2020), int64(77), int64(0), nil, nil},
{"Apple", int64(2021), int64(1), nil, nil, nil},
{"Kale", int64(2020), int64(51), int64(23), int64(45), int64(3)},
{"Kale", int64(2021), int64(70), int64(85), nil, nil},
},
},
{
name: "UNPIVOT",
query: `
WITH Produce AS (
SELECT 'Kale' as product, 51 as Q1, 23 as Q2, 45 as Q3, 3 as Q4 UNION ALL
SELECT 'Apple', 77, 0, 25, 2)
SELECT * FROM Produce
UNPIVOT(sales FOR quarter IN (Q1, Q2, Q3, Q4))
`,
expectedRows: [][]interface{}{
{"Kale", int64(51), "Q1"},
{"Kale", int64(23), "Q2"},
{"Kale", int64(45), "Q3"},
{"Kale", int64(3), "Q4"},
{"Apple", int64(77), "Q1"},
{"Apple", int64(0), "Q2"},
{"Apple", int64(25), "Q3"},
{"Apple", int64(2), "Q4"},
},
},
{
name: "date_sub",
query: `SELECT DATE_SUB('2023-03-31', INTERVAL 1 MONTH)`,
Expand Down

0 comments on commit d44cbf9

Please sign in to comment.