我有以下查询
SELECT DATEPART(YEAR, Date_Reported) AS 'Year',
DATEPART(MONTH, Date_Reported) AS 'Month',
DATEPART(DAY, Date_Reported) AS 'Day',
COUNT(*) AS 'Transactions'
FROM TX
WHERE Date_Reported >= DATEADD(day,-7, GETDATE())
GROUP BY DATEPART(DAY, Date_Reported),
DATEPART(MONTH, Date_Reported),
DATEPART(YEAR, Date_Reported)
ORDER BY 'Year',
'Month',
'Day'
它给我的是最近7天的交易,但是当天交易为0时,它不会显示任何行。我想要的是没有行在事务列下显示为0值,如下所示:
YEAR | MONTH | DAY | TRANSACTIONS
2018 | 9 | 4 | 2
2018 | 9 | 5 | 2
2018 | 9 | 6 | 0
2018 | 9 | 7 | 5
2018 | 9 | 8 | 2
2018 | 9 | 9 | 0
2018 | 9 | 10 | 0
有什么想法吗?
答案 0 :(得分:0)
这是一种可能的解决方案:
WITH LastDays AS --Base table
(
SELECT CAST(DATEADD(DAY,-D,SYSDATETIME()) AS Date) D FROM (VALUES (0),(1),(2),(3),(4),(5),(6)) T(D)
), TX AS --Demo data
(
SELECT * FROM (VALUES
(CAST(SYSDATETIME() AS Date)),
(CAST(DATEADD(DAY,-2,SYSDATETIME()) AS Date))
) T(Date_Reported)
)
SELECT DATEPART(YEAR, D) AS 'Year',
DATEPART(MONTH, D) AS 'Month',
DATEPART(DAY, D) AS 'Day',
COUNT(Date_Reported) AS 'Transactions'
FROM LastDays
LEFT JOIN TX ON Date_Reported=D
GROUP BY DATEPART(DAY, D),
DATEPART(MONTH, D),
DATEPART(YEAR, D)
ORDER BY 'Year',
'Month',
'Day'
答案 1 :(得分:0)
这是解决方案,
首先,您必须创建日期表作为基本表,因为您没有显示TX
中的日期记录,因为您显示为0。
按照下面的查询,您可以创建该表并将其存储到临时表中。
;WITH cte AS (
SELECT cast(GETDATE() as date) AS myDate
UNION ALL
SELECT cast( DATEADD(DAY,-1,myDate) as date)
FROM cte
where myDate >= DATEADD(day,-7, GETDATE())
)
SELECT myDate Into #dateTable
FROM cte
第二,您可以按照以下所示使用左联接#dateTable
和您的TX
。
select DATEPART(YEAR, myDate) AS 'Year',
DATEPART(MONTH, myDate) AS 'Month',
DATEPART(DAY, myDate) AS 'Day',
Count(Date_Reported) as 'Transactions'
from #dateTable
LEFT JOIN #Tempdata on CAST(Date_Reported as DATE) = CASt(myDate as date)
GROUP BY DATEPART(DAY, myDate),
DATEPART(MONTH, myDate),
DATEPART(YEAR, myDate)
ORDER BY 'Year',
'Month',
'Day'