如何从系统版本表中获取多个日期

时间:2019-07-09 08:08:40

标签: sql-server

我有一个名为Archiv.liste的系统版本表,我想将12个日期与Profit的总和进行比较。

有没有比通过UNION更好的方法了?

SELECT BranchCO AS Branch --> BAB01
      ,CAST('02.18.2019' AS DATE) AS Stichtag
      ,MONTH(ServiceDate) AS Leistungsmonat
      ,SUM(Profit) AS ProfitSum
FROM archiv.Liste FOR SYSTEM_TIME AS OF '02.18.2019' TL 
GROUP BY  BranchCO,MONTH(ServiceDate)
UNION 
SELECT BranchCO AS Branch --> BAB02
      ,CAST('03.18.2019' AS DATE) AS Stichtag
      ,MONTH(ServiceDate) AS Leistungsmonat
      ,SUM(Profit) AS ProfitSum
FROM archiv.Liste FOR SYSTEM_TIME AS OF '03.18.2019' TL 
GROUP BY  BranchCO,MONTH(ServiceDate)
UNION 
SELECT BranchCO AS Branch --> BAB03
      ,CAST('04.15.2019' AS DATE) AS Stichtag
      ,MONTH(ServiceDate) AS Leistungsmonat
      ,SUM(Profit) AS ProfitSum
FROM archiv.Liste FOR SYSTEM_TIME AS OF '04.15.2019' TL 
GROUP BY  BranchCO,MONTH(ServiceDate)

有没有这样的命令

SELECT * FROM archiv.Liste FOR SYSTEM_TIME AS IN ('02.18.2019','03.18.2019','04.15.2019')

2 个答案:

答案 0 :(得分:0)

尝试以下查询:    SELECT * FROM archiv.List FOR SYSTEM_TIME CONTAINED IN('02 .18.2019','03.18.2019','04.15.2019')

答案 1 :(得分:0)

也许您可以从Temporal和History表中(通过ALL关键字获取所有行版本之后,才能进行日期过滤。您可以使用句点开始和结束列名称更改StartTimeEndTime列。

SELECT 
      BranchCO AS Branch --> BAB01
     ,CAST(StartTime AS DATE) AS Stichtag
     ,MONTH(ServiceDate) AS Leistungsmonat
     ,SUM(Profit) AS ProfitSum
FROM archiv.Liste
FOR SYSTEM_TIME ALL
WHERE 
    (StartTime <= '02.18.2019' AND EndTime > '02.18.2019')
    OR  (StartTime <= '03.18.2019' AND EndTime > '03.18.2019')
    OR  (StartTime <= '04.15.2019' AND EndTime > '04.15.2019')