您好我正在为SSRS中的报告开发数据集 我有一个查询,它给出了积压中的总请求数:
SELECT
COUNT(*) as NB
FROM p_rqt WITH (NOLOCK)
INNER JOIN p_cpy WITH (NOLOCK) ON p_cpy.CpyInCde = p_rqt.OrigCpyInCde
WHERE
CpyTypInCde IN (27, 31)
AND p_rqt.RqtNatInCde IN (74, 75, 76)
AND HeadRqtInCde = 0
AND p_rqt.OrigCpyInCde LIKE CASE WHEN @Client = 0 THEN '%' ELSE @Client END
AND ((RcvDte < DATEADD(day, 1, @DateDeb) AND RqtEndDte IS NULL) OR
(RcvDte < DATEADD(day, 1, @DateDeb) AND RqtEndDte > DATEADD(day, 1, @DateDeb)))
我想要检索每天剩余的总金额。 我尝试了很多这样的事情:
SELECT CONVERT(date,rcvdte,103), count(*) as nb
FROM p_rqt p WITH (NOLOCK)
INNER JOIN p_cpy WITH (NOLOCK) ON p_cpy.CpyInCde = p.OrigCpyInCde
WHERE
CpyTypInCde IN (27, 31)
AND p.RqtNatInCde IN (74, 75, 76)
AND HeadRqtInCde = 0
AND ((RcvDte < DATEADD(day, 1, '20170901') AND RqtEndDte IS NULL) OR (RcvDte < DATEADD(day, 1, '20170901') AND RqtEndDte > DATEADD(day, 1, '20170901')))
group by CONVERT(date,rcvdte,103)
order by CONVERT(date,rcvdte,103)
我尝试了内连接子查询,Sum和其他东西 但我能做的就是每天增加记录数量 我想要这样的东西:
date: NB:
01/01/2017 1950
02/01/2017 1954 (+4 items)
03/01/2017 1945 (-9 items)
谢谢
答案 0 :(得分:0)
使用LAG
:
WITH cte AS (
SELECT
CONVERT(date, rcvdte, 103) AS date,
COUNT(*) AS nb
FROM p_rqt p WITH (NOLOCK)
INNER JOIN p_cpy WITH (NOLOCK)
ON p_cpy.CpyInCde = p.OrigCpyInCde
WHERE
CpyTypInCde IN (27, 31) AND
p.RqtNatInCde IN (74, 75, 76) AND
HeadRqtInCde = 0 AND
((RcvDte < DATEADD(day, 1, '20170901') AND RqtEndDte IS NULL) OR (RcvDte < DATEADD(day, 1, '20170901') AND RqtEndDte > DATEADD(day, 1, '20170901')))
GROUP BY CONVERT(date, rcvdte, 103)
ORDER BY CONVERT(date, rcvdte, 103)
)
SELECT
t1.date,
(SELECT SUM(t2.nb) FROM cte t2 WHERE t2.date <= t1.date) AS nb,
CASE WHEN t1.nb - LAG(t1.nb, 1, t1.nb) OVER (ORDER BY t1.date) > 0
THEN '(+' + (t1.nb - LAG(t1.nb, 1, t1.nb) OVER (ORDER BY t1.date)) + ' items)'
ELSE '(' + (t1.nb - LAG(t1.nb, 1, t1.nb) OVER (ORDER BY t1.date)) + ' items)'
END AS difference
FROM cte t1
ORDER BY t1.date;
答案 1 :(得分:0)
所以我找到了一个解决方案,但它真的很慢, 我仍然会发布答案
DECLARE @Tb TABLE ( Colonne1 Datetime, Colonne2 INT )
DECLARE @Debut Datetime = '01/09/2017'
WHILE @Debut < '13/09/2017'
BEGIN
DECLARE @Compteur int = (
SELECT
COUNT(1) NB
FROM p_rqt WITH (NOLOCK)
INNER JOIN p_cpy WITH (NOLOCK) ON p_cpy.CpyInCde = p_rqt.OrigCpyInCde
WHERE
CpyTypInCde IN (27, 31)
AND p_rqt.RqtNatInCde IN (74, 75, 76)
AND HeadRqtInCde = 0
AND p_rqt.OrigCpyInCde LIKE '%'
AND (
(RcvDte < @Debut AND RqtEndDte IS NULL)
OR
(RcvDte < @Debut AND RqtEndDte > @Debut)
)
)
INSERT INTO @Tb (Colonne1, Colonne2) VALUES (@Debut, @Compteur)
SET @Debut = DATEADD(day, 1, @Debut)
IF @Debut > '13/09/2017'
BREAK
ELSE
CONTINUE
END
SELECT * FROM @Tb