[英]SQL - How to return every day of month even with no data available
Below is my initial query and the data it returns:以下是我的初始查询及其返回的数据:
SELECT
User
,Client
,Date
,Total
FROM SampleTable
WHERE Date BETWEEN '20200101' AND '20200131'
Instead, I would like it to include a row for every day in the month like the table below:相反,我希望它在一个月中的每一天都包含一行,如下表所示:
I have a standard ANSI date table already;我已经有了一个标准的 ANSI 日期表; however, I've been unable to find a solution that includes dimensions that also need to be joined on (User/Client):
但是,我一直无法找到包含还需要加入(用户/客户端)维度的解决方案:
I don't want my table to look like this:我不希望我的桌子看起来像这样:
I am thinking my answer lies somewhere in the cross apply/subquery realm, but am new to SQL, so I'm having trouble understanding exactly how that will be done.我认为我的答案位于交叉应用/子查询 realm 的某处,但我是 SQL 的新手,所以我无法准确理解如何完成。 Any help would be appreciated.
任何帮助,将不胜感激。 Thanks!
谢谢!
If you have all dates in the table, you can use that as the source.如果表中有所有日期,则可以将其用作来源。 Then a
cross join
and left join
:然后是
cross join
和left join
:
select uc.user, uc.client, d.date,
coalesce(st.total, 0)
from (select distinct user, client
from sampletable
) uc cross join
(select distinct date
from sampletable
) d left join
sampletable st
on st.user = uc.user and st.client = uc.client and
st.date = d.date;
If the base table doesn't have all the dates you can generate them in various ways:如果基表没有所有日期,您可以通过多种方式生成它们:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.