我在SSRS中使用了一个查询,用于按每个日期显示所有客户端名称,记录数。我的问题是下面的查询只显示那个特定日期有数据的人。很多时候,客户可能没有几天或几周的数据,而且此报告仅显示客户端有数据。我可以显示客户的完整列表,即使他们可能会返回0条记录吗?我不知道使用我的CTE设置是否可行。
例如:
客户A:0
客户B:10
客户C:0
客户D:35
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
WITH CTE AS (
select c.ClientName, convert(char(10), h.RecordDate, 120) As Date, COUNT(*) As Count
from clientHistory h
inner join client c on c.ClientID = h.clientid
where convert(char(10), h.RecordDate, 120) > DATEADD(DAY, -15, GETDATE())
group by c.ClientName, convert(char(10), h.RecordDate, 120)
)
select c.ClientName, Date, Sum(Count) As Count
from CTE
group by c.ClientName, Date order by ClientName
答案 0 :(得分:1)
如果要检索每个客户端,请从客户端表中选择并左键加入clientHistory表:
select c.ClientName, convert(char(10), h.RecordDate, 120) As Date, COUNT(*) As Count
from client c
left join clientHistory h
on c.ClientID = h.clientid
and convert(char(10), h.RecordDate, 120) > DATEADD(DAY, -15, GETDATE())
group by c.ClientName, convert(char(10), h.RecordDate, 120)
答案 1 :(得分:0)
我猜你需要日历表
;WITH calender
AS (SELECT convert(date,'2014-01-01') AS dates -- Replace with startdate
UNION ALL
SELECT Dateadd(dd, 1, dates)
FROM calender
WHERE dates < '2014-12-31'), -- Replace with enddate
CTE1
AS (SELECT *
FROM (SELECT DISTINCT ClientName
FROM client) a
CROSS JOIN calender),
cte2
AS (SELECT c.ClientName,
CONVERT(CHAR(10), h.RecordDate, 120) AS Date,
Count(*) AS Count
FROM clientHistory h
INNER JOIN client c
ON c.ClientID = h.clientid
WHERE CONVERT(CHAR(10), h.RecordDate, 120) > Dateadd(DAY, -15, Getdate())
GROUP BY c.ClientName,
CONVERT(CHAR(10), h.RecordDate, 120))
SELECT a.ClientName,
a.Dates,
Sum(Count) AS Count
FROM CTE1 a
LEFT JOIN cte2 b
ON a.dates = b.Date
AND a.ClientName = b.ClientName
GROUP BY a.ClientName,
a.Dates
ORDER BY ClientName
Option (Maxrecursion 0)