我有这张表:
Label || Item_Type || Item_Name || Price || Item_Type_Median || Label_Median_Price Tag || C || Tag C1 || 231 || 312 || 416 Tag || C || Tag C2 || 312 || 312 || 416 Tag || C || Tag C3 || 416 || 312 || 416 Tag || E || Tag E1 || 523 || 523 || 416 Tag || E || Tag E2 || 152 || 523 || 416 Tag || E || Tag E3 || 629 || 523 || 416 Tag || E || Tag E4 || 29 || 523 || 416 Tag || E || Tag E5 || 727 || 523 || 416 Tag || F || Tag F1 || 671 || 671 || 416 Tag || F || Tag F2 || 1002 || 671 || 416 Tag || F || Tag F3 || 96 || 671 || 416 No_Tag|| G || Tag G || 61 || 61 || 170 No_Tag|| H || Tag H1 || 802 || 419 || 170 No_Tag|| H || Tag H2 || 36 || 419 || 170 No_Tag|| J || Tag J || 102 || 102 || 170 No_Tag|| K || Tag K || 546 || 546 || 170 No_Tag|| M || Tag M || 238 || 238 || 170
我需要获得如下表格,Total_Price
列显示每个Item_Type
的总价格以及每个Label
的总价格和Median_Price
列显示每个Item_Type
和每个Label
的中位数价格:
Label || Item_Type || Total_Price || Median_Price Tag || NULL || 4788 || 416 Tag || C || 959 || 312 Tag || E || 2060 || 523 Tag || F || 1769 || 671 No_Tag|| NULL || 1785 || 170 No_Tag|| G || 61 || 61 No_Tag|| H || 838 || 419 No_Tag|| J || 102 || 102 No_Tag|| K || 546 || 546 No_Tag|| M || 238 || 238
我已经能够按预期获得表格中的Item_Type
中位数价格,但我无法弄清楚如何在同一列中获得Label
中位数价格。
SELECT [Label],[Item_Type],SUM([Item_Price]) [Total_Price],AVG([Item_Type_Median]) [Median_Price]
FROM Item_Price_Data
GROUP BY [Label],[Item_Type]
UNION ALL
SELECT [Label],NULL,SUM([Item_Price]),
CASE
WHEN [Item_Type] IS NULL THEN [Label_Median_Price]
ELSE AVG([Item_Type_Median])
END
FROM Item_Price_Data
GROUP BY [Label]
ORDER BY [Label],[Item_Type];
答案 0 :(得分:1)
如果您只是将CASE WHEN
子句替换为AVG([Label_Median_Price])
,您的查询就会显示出来:
SELECT [Label], [Item_Type], SUM([Item_Price]) [Total_Price],
AVG([Item_Type_Median]) [Median_Price]
FROM Item_Price_Data
GROUP BY [Label], [Item_Type]
UNION ALL
SELECT [Label], NULL, SUM([Item_Price]), AVG([Label_Median_Price])
FROM Item_Price_Data
GROUP BY [Label]
ORDER BY [Label],[Item_Type];