SqlServer:按月选择和分组

时间:2014-05-14 02:24:58

标签: sql

我想编写一个SQL来计算过去六个月的销售额,就像下面的代码一样。

SELECT
    MONTH (pc.createTime) AS MONTH,
    SUM (partsModelSum) AS totalSum
FROM
    partscontractlinkmodel AS pl
RIGHT JOIN partscontract pc ON pl.partsContractID = pc.partsContractID
AND pc.companyID = 8
AND pc.createTime BETWEEN '2013/11/01 00:00:00'
AND '2014/04/30 23:59:59'
WHERE
    pl.partsModelID = 21028
GROUP BY
    MONTH (pc.createTime)
ORDER BY
    totalSum DESC

结果是:

month   totalSum
4       24

但问题出现的问题是,查询结果中没有出现销售记录月份,我希望结果中没有销售记录,值为0

像这样:

month   totalSum
4       24
3       0
2       0
1       0
12      0
11      0

那么,如何修改sql解决我的问题;) 感谢

3 个答案:

答案 0 :(得分:0)

如果您每个月都有一些数据,则可以使用条件聚合:

SELECT MONTH (pc.createTime) AS MONTH,
       SUM(CASE WHEN pl.partsModelID = 21028 THEN partsModelSum END) AS totalSum
FROM partscontract pc LEFT JOIN
     partscontractlinkmodel  pl
     ON pl.partsContractID = pc.partsContractID AND
        pc.companyID = 8 AND
        pc.createTime BETWEEN '2013/11/01 00:00:00' AND '2014/04/30 23:59:59'
GROUP BY
    MONTH(pc.createTime)
ORDER BY totalSum DESC;

如果这不起作用,则需要使用子查询或CTE生成月份列表。

答案 1 :(得分:0)

从表或子查询中获取月份列表。左连接月表(查询和零件合同)通过月(createTime)和月/从表/子查询。左连接partcontract和partscontractlinkmodel就像你做的那样。见下面的样本:

; WITH CTE_Month
作为

选择1作为MonthN
UNION
SELECT 2作为MonthN
UNION
SELECT 3作为MonthN
UNION
SELECT 4作为MonthN
UNION
选择5作为MonthN
UNION
选择6作为MonthN
UNION
SELECT 7作为MonthN
UNION
SELECT 8作为MonthN
UNION
选择9作为MonthN
UNION
SELECT 10作为MonthN
UNION
SELECT 11作为MonthN
UNION
选择12作为MonthN
),
SELECT
    N.MonthN AS MONTH,
    SUM(ISNULL(partsModelSum,0))AS totalSum

    CTE_Month M
    LEFT JOIN partscontract pc ON MONTH(pc.createTime)= N.MonthN
    LEFT JOIN partscontractlinkmodel AS pl
      ON pl.partsContractID = pc.partsContractID
      AND pc.companyID = 8
      和pc.createTime BETWEEN' 2013/11/01 00:00:00'
      AND' 2014/04/30 23:59:59'
WHERE
    pl.partsModelID = 21028
GROUP BY     N.MonthN
订购单     totalSum DESC

答案 2 :(得分:0)

你可以创建一个月份列表的临时表,并在连接中使用它...可能是这样的......

SELECT
    MONTH (pc.createTime) AS MONTH,
    SUM (partsModelSum) AS totalSum
FROM
    (select 1 monthNum union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9 union select 10 union select 11 union select 12 ) MonthList
    left join partscontract pc ON MonthList.monthNum = MONTH(pc.createTime)
    left join partscontractlinkmodel AS pl ON pc.partsContractID = pl.partsContractID
            AND pc.companyID = 8
            AND pc.createTime BETWEEN '2013/11/01 00:00:00'
            AND '2014/04/30 23:59:59'
WHERE
    pl.partsModelID = 21028
GROUP BY
    MONTH (pc.createTime)
ORDER BY
    totalSum DESC