Skip to content

Commit 9184533

Browse files
authored
Merge pull request #10733 from SkyFan2002/pivot
feat: PIVOT result column
2 parents 6f5ed62 + 5e42037 commit 9184533

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

src/query/sql/src/planner/binder/select.rs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -772,6 +772,17 @@ impl<'a> SelectRewriter<'a> {
772772
.collect(),
773773
}
774774
}
775+
776+
// For Expr::Literal, expr.to_string() is quoted, sometimes we need the raw string.
777+
fn raw_string_from_literal_expr(expr: &Expr) -> Option<String> {
778+
match expr {
779+
Expr::Literal { lit, .. } => match lit {
780+
Literal::String(v) => Some(v.clone()),
781+
_ => Some(expr.to_string()),
782+
},
783+
_ => None,
784+
}
785+
}
775786
}
776787

777788
impl<'a> SelectRewriter<'a> {
@@ -841,10 +852,12 @@ impl<'a> SelectRewriter<'a> {
841852
pivot.value_column.clone(),
842853
value.clone(),
843854
));
855+
let alias = Self::raw_string_from_literal_expr(value)
856+
.ok_or_else(|| ErrorCode::SyntaxException("Pivot value should be literal"))?;
844857
new_select_list.push(Self::target_func_from_name_args(
845858
new_aggregate_name.clone(),
846859
args,
847-
None,
860+
Some(Self::ident_from_string(&alias)),
848861
));
849862
}
850863

@@ -875,14 +888,14 @@ impl<'a> SelectRewriter<'a> {
875888
vec![Self::expr_literal_array_from_vec_ident(
876889
unpivot.names.clone(),
877890
)],
878-
None,
891+
Some(unpivot.column_name.clone()),
879892
));
880893
new_select_list.push(Self::target_func_from_name_args(
881894
Self::ident_from_string("unnest"),
882895
vec![Self::expr_column_ref_array_from_vec_ident(
883896
unpivot.names.clone(),
884897
)],
885-
None,
898+
Some(unpivot.value_column.clone()),
886899
));
887900

888901
if let Some(ref mut new_stmt) = self.new_stmt {

tests/sqllogictests/suites/query/pivot.test

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ INSERT INTO monthly_sales VALUES
2323

2424

2525
query IIIII
26+
SELECT empid,jan,feb,mar,apr FROM
2627
SELECT *
2728
FROM monthly_sales
2829
PIVOT(SUM(amount) FOR MONTH IN ('JAN', 'FEB', 'MAR', 'APR'))

tests/sqllogictests/suites/query/unpivot.test

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ ORDER BY empid;
2626
3 cars April 50
2727

2828
query IIII
29+
SELECT empid,dept,month,sales FROM
2930
SELECT * FROM monthly_sales_1
3031
UNPIVOT(sales FOR month IN (jan, feb, mar, april))
3132
ORDER BY empid;

0 commit comments

Comments
 (0)