How do I get values for all months in T-SQL

馋奶兔 提交于 2020-01-02 18:34:38

问题


I have a query that I would like to display all months for the year regardless if they have sales for that month or not. I know the issue is with the Group By, but how do I change the query so I don't need it?

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)

回答1:


Try this:-

  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



回答2:


You need a table that has those values first, and use it to do a LEFT JOIN with your SalesData table:

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

In my answer I'm using the spt_values table to get the 12 months.




回答3:


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


来源:https://stackoverflow.com/questions/20690965/how-do-i-get-values-for-all-months-in-t-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!