基于月列对数据进行分组的最佳方法是什么?

时间:2018-07-25 18:13:45

标签: sql-server tsql

因此,基本上,我正在制作一个报告,显示从1月到7月任何给定月份内所有产品的最高价格。理想情况下,我希望每个零件号1行,并显示从1月到1月的最高价格月。这是我的代码和下面的结果照片:

SELECT
    pd.PartNo,
    CASE
        WHEN MONTH(p.DateEnt) = 1 AND YEAR(p.DateEnt) = 2018 THEN MAX(pd.UnitCost)
        END AS [Jan 2018],
    CASE
        WHEN MONTH(p.DateEnt) = 2 AND YEAR(p.DateEnt) = 2018 THEN MAX(pd.UnitCost)
        END AS [Feb 2018],
    CASE
        WHEN MONTH(p.DateEnt) = 3 AND YEAR(p.DateEnt) = 2018 THEN MAX(pd.UnitCost)
        END AS [Mar 2018],
    CASE
        WHEN MONTH(p.DateEnt) = 4 AND YEAR(p.DateEnt) = 2018 THEN MAX(pd.UnitCost)
        END AS [Apr 2018],
    CASE
        WHEN MONTH(p.DateEnt) = 5 AND YEAR(p.DateEnt) = 2018 THEN MAX(pd.UnitCost)
        END AS [May 2018],
    CASE
        WHEN MONTH(p.DateEnt) = 6 AND YEAR(p.DateEnt) = 2018 THEN MAX(pd.UnitCost)
        END AS [Jun 2018],
    CASE
        WHEN MONTH(p.DateEnt) = 7 AND YEAR(p.DateEnt) = 2018 THEN MAX(pd.UnitCost)
        END AS [Jul 2018]
FROM PODet pd
    JOIN PO p ON pd.PONum = p.PONum
    JOIN Estim e ON pd.PartNo = e.PartNo
WHERE p.DateEnt > '20180101'
GROUP BY pd.PartNo, p.DateEnt
ORDER BY pd.PartNo, p.DateEnt DESC

enter image description here

因此,如果您查看结果并查看PartNo CAB-01,您不仅可以看到它不跨列分组,而且在同一个月内它也没有分组。我究竟做错了什么?提前谢谢

1 个答案:

答案 0 :(得分:2)

您希望每个零件号都有一行,但是在您的GROUP BY子句中,您告诉它每个唯一的日期都产生一行,而每个零件号条目都出现在GROUP BY Pd.PartNo, Pd.DateEnt上。很显然,CAB-01项目在7月有两个不同的日期,因此它有两行的值在'Jul 2018'下;您只是无法确定它们是两个不同的日期,因为确切的日期不是输出的一部分。

要获得所需的内容,您需要从Pd.DateEntGROUP BY子句中删除ORDER BY,并将MAX()从{的内部移到外部{1}}语句,以便CASE仍然有效:

GROUP BY

此外,如图所示,您根本没有在查询中使用ESTIM表,因此您可能想要删除该JOIN;并且如果要包括2018年的全部内容,则应将SELECT pd.PartNo, MAX(CASE WHEN MONTH(p.DateEnt) = 1 AND YEAR(p.DateEnt) = 2018 THEN pd.UnitCost END) AS [Jan 2018], MAX(CASE WHEN MONTH(p.DateEnt) = 2 AND YEAR(p.DateEnt) = 2018 THEN pd.UnitCost END) AS [Feb 2018], MAX(CASE WHEN MONTH(p.DateEnt) = 3 AND YEAR(p.DateEnt) = 2018 THEN pd.UnitCost END) AS [Mar 2018], MAX(CASE WHEN MONTH(p.DateEnt) = 4 AND YEAR(p.DateEnt) = 2018 THEN pd.UnitCost END) AS [Apr 2018], MAX(CASE WHEN MONTH(p.DateEnt) = 5 AND YEAR(p.DateEnt) = 2018 THEN pd.UnitCost END) AS [May 2018], MAX(CASE WHEN MONTH(p.DateEnt) = 6 AND YEAR(p.DateEnt) = 2018 THEN pd.UnitCost END) AS [Jun 2018], MAX(CASE WHEN MONTH(p.DateEnt) = 7 AND YEAR(p.DateEnt) = 2018 THEN pd.UnitCost END) AS [Jul 2018] FROM PODet pd JOIN PO p ON pd.PONum = p.PONum JOIN Estim e ON pd.PartNo = e.PartNo WHERE p.DateEnt > '20180101' GROUP BY pd.PartNo ORDER BY pd.PartNo 的条件更改为WHERE