cant use BETWEEN
即使 BETWEEN 是日期,您也可以inclusive
。对于这种情况,最好使用
startdate>='2012-07-08 ' and enddate<=2013-02-06
因为2013-02-06
将被视为 2013-02-06 00:00:00
12AM
为您的问题尝试此解决方案
DECLARE @temp AS TABLE(Month_Name varchar(25),ContactName varchar(50)) -- newly added
;WITH cte
AS
(
SELECT datename(month, @startdate) AS [Month_Name], @startdate AS dat
UNION ALL
SELECT datename(month, DateAdd(Month, 1, dat)), DateAdd(Month, 1, dat)
FROM cte
WHERE DateAdd(Month, 1, dat) < @enddate
)
INSERT INTO @temp
SELECT c.Month_Name,Cs.username
FROM cte c CROSS JOIN usertbale Cs
ORDER BY c.Month_Name
SELECT c.Month_Name,c.username,ISNULL(tt.coun,0) as coun
FROM @temp c LEFT JOIN
(
SELECT datename(month,OrderDate) AS month_Name
,count(OrderID) as coun
,ContactName
FROM tblpublisher p INNER JOIN tbluser u ON u.userid=p.userid
GROUP BY month_Name,datename(month,publishdate)
) as tt
ON c.Month_Name=tt.month_Name AND c.username=tt.username
编辑
在上面的查询中使用pivot
,您可以获得与您的问题一样的确切结果
检查这个