在同一列中合并2个不同的中值

时间:2018-04-12 20:21:25

标签: sql sql-server sql-server-2012

我有这张表:

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];

1 个答案:

答案 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];