簡體   English   中英

sql查詢獲取從一月到當月的所有數據,即使沒有記錄

[英]sql query get all data from Jan to current month even if there are no records

我對sql不好,所以任何幫助世界都很棒

我有一個SQL查詢,該查詢獲取從1月到本月注冊的記錄

我的代碼示例

SELECT DatePart(YEAR, p.createStamp) as TheYear, DatePart(MONTH, p.createStamp) as TheMonth ,  COUNT(p.pId) AS TOTALCOUNT 
FROM profile p with(nolock)
where DatePart(YEAR, p.createStamp) = DATEPART(YEAR, GETDATE())
GROUP BY YEAR(p.createStamp), MONTH(p.createStamp)
ORDER BY YEAR(p.createStamp), MONTH(p.createStamp)

查詢將如何帶回

2月= 2、3月= 3、4月= 4和5月= 5

我想讓它帶回Jan = 1(總數為0)和June = 6(總數為0)以及任何想法如何做到這一點?

謝謝。

這是創建月/年組合並將其用作查詢基礎的循環:

declare @startDate as datetime
set @startDate = '1/1/13'

declare @currentDate as datetime
set @currentDate = '6/6/13'

select
     month(@currentDate) as monthOfDate
    ,year(@currentDate) as yearOfDate
into #allDates
where 1=0

while (@startDate <= @currentDate)
begin
    insert into #allDates values (month(@startDate),year(@startDate))
    set @startDate = dateadd(m,1,@startDate)
end

select 
     _monthYear.yearofDate
    ,_monthYear.monthOfDate
    , COUNT(p.pId) as total
from #allDates _monthYear
left join profile p with(nolock)
    on month(p.createStamp) = _monthYear.monthOfDate
    and year(p.createStamp) = _monthYear.yearOfDate
group by
     _monthYear.yearofDate
    ,_monthYear.montOfDate

drop table #allDates

您無法選擇不存在的內容,因此我建議制作一個查詢表:

CREATE TABLE #Months (Year_ INT, Month_ INT)
GO
SET NOCOUNT ON
DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=20)
BEGIN
--Do Stuff
INSERT INTO #Months
SELECT YEAR(DATEADD(MONTH,@intflag,'20121201')),MONTH(DATEADD(MONTH,@intflag,'20121201'))
SET @intFlag = @intFlag + 1
END
GO

您可以將“ 20”更改為您想要的任何月份,並將兩個位置的“ 20121201”更改為要開始查找的月份之前的一個月。

然后,加入該表,我相信以下方法將起作用:

SELECT m.Year_ as TheYear, m.Month_ as TheMonth ,  ISNULL(COUNT(p.pId),0) AS TOTALCOUNT 
FROM profile p
RIGHT JOIN #Months m
ON DatePart(YEAR, p.createStamp) = m.Year_
AND  DatePart(MONTH, p.createStamp) = m.Month_
where DatePart(YEAR, p.createStamp) = DATEPART(YEAR, GETDATE())
GROUP BY m.Year_, m.Month_
ORDER BY  m.Year_, m.Month_

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM