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)
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
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.
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