表CTE和日期递归

时间:2018-09-02 20:29:48

标签: sql-server tsql

以下查询已在附件图像Fichiers recus.中返回结果1 我也想拥有结果2,但我不知道该怎么做。 谢谢您的帮助。

DECLARE @dateDebut DATE = 2018-07-10
DECLARE @dateFin DATE = 2018-07-14
DECLARE @cols VARCHAR(MAX)
DECLARE @cols VARCHAR(MAX)
DECLARE @query VARCHAR(MAX)
DECLARE @sum_cols VARCHAR(MAX)

WITH Dates
AS (
SELECT [Date1] = CONVERT(Date,@dateDebut)
UNION ALL
SELECT [Date1] = DATEADD(DAY,1,[Date1])
FROM Dates
WHERE DATEADD(DAY,1,[Date1]) < @dateFin
)
SELECT LEFT(CONVERT(VARCHAR,[Date1],20),10) Date
INTO #DatesSerie
FROM Dates
OPTION (MAXRECURSION 45);

SET @cols = STUFF(( SELECT distinct ',' + QUOTENAME(d.Date)
                    FROM #DatesSerie d 
                    FOR XML PATH(''), TYPE
                    ).value('.', 'NVARCHAR(MAX)'),1,1,'')


SET @query = 'SELECT Reg, Trad, Rac, '+ @sum_cols +'
              FROM FichiersRecus
              PIVOT (
                      COUNT(FileName)
                      FOR DateFichier IN (' + @cols + ')
                    ) AS MYPIVOT
              GROUP BY Reg,Trad,Rac
              ORDER BY '+ @dateDebut +' DESC, Reg,Trad ASC ';


EXECUTE (@query)    

1 个答案:

答案 0 :(得分:1)

结果2不需要动态SQL。

只需将参考表与日期交叉联接,然后将其左联接到FichiersRecus。

DECLARE @dateDebut DATE = '2018-07-10';
DECLARE @dateFin DATE = '2018-07-14';

WITH DATES AS (
  SELECT @dateDebut AS DateFichier
  UNION ALL
  SELECT DATEADD(DAY, 1, DateFichier)
  FROM DATES
  WHERE DateFichier < @dateFin
)
SELECT d.DateFichier, t1.Reg, t1.Trad, t2.Rac, f.FileName
FROM DATES AS d
CROSS JOIN Table1 AS t1
CROSS JOIN Table2 AS t2
LEFT JOIN FichiersRecus AS f 
  ON (f.DateFichier = d.DateFichier
  AND f.Reg = t1.Reg 
  AND f.Trad = t1.Trad 
  AND f.Rac = t2.Rac)
ORDER BY d.DateFichier, t1.Reg, t1.Trad, t2.Rac;