加入CTE按月/年分组

时间:2019-03-25 20:47:23

标签: sql tsql

我有多个CTE,它们导致以下通用表结构:

Year | Month | Total_Purchases_Product_Line_X

这些代表按月和按年份划分的跨多个产品系列的购买。

例如)

SELECT * FROM cte_line_x    

Year | Month | Total_Purchases_Product_Line_X
2018    01      256
2018    02      192

SELECT * FROM cte_line_y    

Year | Month | Total_Purchases_Product_Line_Y
2018    01      76
2018    02      59

我想创建类似以下内容

Year | Month | Total_Purchases_Line_X | Total_Purchases_Line_Y | Total_Purchases_Line_Z
2018    01     256                       76
2018    02     192                       59

每个产品系列的总购买额合并在一起。但是,在将每个CTE的日期合并在一起时,我遇到了一些问题。 这是我尝试过的:

SELECT 
    cte_product_x.Month, 
    cte_product_x.Year, 
    cte_product_x.total as Total_X, 
    cte_product_y.total as Total_Y, 
    cte_product_z.total as Total_Z
FROM 
     cte_product_x
LEFT JOIN
     cte_product_y ON
     cte_product_y.year = cte_product_x.year
     AND
     cte_product_y.month = cte_product_x.month
LEFT JOIN
     cte_product_z ON
     cte_product_z.year = cte_product_x.year
     AND
     cte_product_z.month = cte_product_x.month
 GROUP BY 
    cte_product_x.Month, 
    cte_product_x.Year
  ORDER BY 
    cte_product_x.Month, 
    cte_product_x.Year

我尝试将SELECT更改为:

SELECT 
    cte_product_x.Month, 
    cte_product_x.Year, 
    MAX(cte_product_x.total as Total_X), 
    MAX(cte_product_y as Total_Y), 
    MAX(cte_product_z as Total_Z)

但是,它仅适用于“ Total_X”。其他列的计数是所有月份分组总和中找到的最大值。我不明白为什么。

1 个答案:

答案 0 :(得分:2)

这行不通吗?

SELECT x.Month, x.Year, x.total as Total_X, 
       y.total as Total_Y, z.total as Total_Z
FROM cte_product_x x JOIN
     cte_product_y y
     ON y.year = x.year AND y.month = x.month JOIN
     cte_product_z z
     ON z.year = x.year AND z.month = x.month
ORDER BY x.Month, x.Year;

至少它适用于您的样本数据。