如何在T-SQL中获取所有月份的值

时间:2013-12-19 20:22:52

标签: sql-server tsql sql-server-2012-express

我有一个查询,我希望显示一年中的所有月份,无论他们是否有该月的销售额。我知道问题出在Group By上,但是如何更改查询以便我不需要它?

SELECT
   ISNULL(MONTH(sd.SBINDT),0) AS MonthSold,
   SUM(sd.SBQSHP) AS QtySold
FROM
   dbo.SalesData sd
WHERE
   sd.SBTYPE = 'O'
   AND sd.SBITEM = @Part
   AND YEAR(sd.SBINDT) = @Year
   AND sd.DefaultLocation = @Location
GROUP BY MONTH(sd.SBINDT)

3 个答案:

答案 0 :(得分:1)

试试这个: -

  SELECT M.Months  AS MonthSold,D.QtySold as QtySold

  FROM (  SELECT distinct(MONTH(sd.SBINDT))as Months from dbo.SalesData sd)M
  left join 
    (
           SELECT MONTH(sd.SBINDT) AS MonthSold,SUM(sd.SBQSHP) AS QtySold
           FROM dbo.SalesData sd
     WHERE  sd.SBTYPE = 'O'
       AND sd.SBITEM = @Part
       AND YEAR(sd.SBINDT) = @Year
       AND sd.DefaultLocation = @Location
   GROUP BY MONTH(sd.SBINDT)
   )D
ON M.Months = D.MonthSold

答案 1 :(得分:0)

您需要一个首先包含这些值的表,并使用它来LEFT JOINSalesData

SELECT  M.MonthNumber AS MonthSold,
        SD.QtySold
FROM (  SELECT number AS MonthNumber
        FROM master.dbo.spt_values
        WHERE type = 'P'
        AND number BETWEEN 1 AND 12) M
LEFT JOIN ( SELECT  MONTH(SBINDT) MonthSold,
                    SUM(SBQSHP) QtySold
            FROM dbo.SalesData
            WHERE SBTYPE = 'O'
            AND SBITEM = @Part
            AND YEAR(SBINDT) = @Year
            AND DefaultLocation = @Location
            GROUP BY MONTH(SBINDT)) SD
    ON M.MonthNumber = SD.MonthSold

在我的回答中,我使用spt_values表来获得12个月。

答案 2 :(得分:0)

SELECT
   MonthSold,
   ISNULL(SUM(sd.SBQSHP),0) AS QtySold
FROM
   dbo.SalesData sd
RIGHT OUTER JOIN (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)) c(MonthSold) ON MonthSold = MONTH(SBINDT)
WHERE
   sd.SBTYPE = 'O'
   AND sd.SBITEM = @Part
   AND YEAR(sd.SBINDT) = @Year
   AND sd.DefaultLocation = @Location
GROUP BY MonthSold