declare @temp table (ddate datetime)
insert @temp
select DATEDIFF(d,0,CONVERT(smalldatetime,'09/30/2012') -Number)
from master..spt_values
where type='p' and number < DatePart(d,'09/30/2012')
order by 1
DECLARE @DeptCode int =1
-- 显示特定日期数据
select ComplaintMedia_Abbri,
ddate,COUNT(ComplaintMedia) as c
from Complaint
INNER JOIN @temp
ON convert(datetime,convert(varchar(10),ComplaintDate,101),101)=convert(datetime,convert(varchar(10),ddate,101),101)
WHERE isnull(Receivedby_Dept,Relatesto_Dept)=1
group by ComplaintMedia_Abbri,ddate
order by ddate,ComplaintMedia_Abbri
-- 显示截至日期的特定日期数据运行总计
select ComplaintMedia_Abbri,ddate,
COUNT(ComplaintMedia_Abbri) as c
from Complaint
INNER JOIN @temp
ON convert(datetime,convert(varchar(10),ComplaintDate,101),101)<=convert(datetime,convert(varchar(10),ddate,101),101)
WHERE isnull(Receivedby_Dept,Relatesto_Dept)=1
group by ComplaintMedia_Abbri,ddate
我想在一个 sql 查询结果中显示截至日期和今天(那天)记录的运行总计.....
在加入时有两个不同的条件。
预期结果应该是这样的
编辑: 我可以通过使用这些查询并加入它们来实现这个结果,但我想在一个查询而不是两个查询中完成这个任务
我目前的方式可以在这里检查。抱歉这么长的问题,但我认为实际上有必要理解问题..
declare @temp table (ddate datetime)
insert @temp
select DATEDIFF(d,0,CONVERT(smalldatetime,'09/30/2012') -Number)
from master..spt_values
where type='p' and number < DatePart(d,'09/30/2012')
order by 1
--select * from @temp
SELECT * FROM
(select ddate,ISNULL(L,0) AS Letter,
ISNULL(P,0) AS Phone,
ISNULL(E,0) AS Email,
ISNULL(W,0) AS WEB
FROM
(
select ComplaintMedia_Abbri,
ddate,COUNT(ComplaintMedia) as c
from Complaint
INNER JOIN @temp
ON convert(datetime,convert(varchar(10),ComplaintDate,101),101)=convert(datetime,convert(varchar(10),ddate,101),101)
WHERE isnull(Receivedby_Dept,Relatesto_Dept)=1
group by ComplaintMedia_Abbri,ddate
) p
pivot (SUM(c) FOR ComplaintMedia_Abbri IN (E,W,L,P)) AS pvt
) AS [A]
INNER JOIN
(
select ddate,ISNULL(L,0) AS LetterTot,
ISNULL(P,0) AS PhoneTot,
ISNULL(E,0) AS EmailTot,
ISNULL(W,0) AS WEBTot
FROM
(
select ComplaintMedia_Abbri,ddate,
COUNT(ComplaintMedia_Abbri) as c
from Complaint
INNER JOIN @temp
ON convert(datetime,convert(varchar(10),ComplaintDate,101),101)<=convert(datetime,convert(varchar(10),ddate,101),101)
WHERE isnull(Receivedby_Dept,Relatesto_Dept)=1
group by ComplaintMedia_Abbri,ddate
) p
pivot (SUM(c) FOR ComplaintMedia_Abbri IN (E,W,L,P)) AS pvt
) AS [B]
ON A.ddate=B.ddate
order by A.ddate