优化上个月用于计算发票的查询

时间:2019-01-04 16:54:09

标签: sql-server tsql

我使用以下查询来计算上个月的发票。我该如何简化呢?

SELECT     
    T1.SNAP, SUM(T3.INVC) AS INV2
FROM
    stg.sales AS T1 
INNER JOIN
    (SELECT     
         CONVERT(NVARCHAR(6), PERI) AS PERI, 
         YEAR(SNAP) AS ANNE, 
         MONTH(SNAP) AS MOIS
     FROM          
         stg.sales
     WHERE      
         (DAY(SNAP) = 1)
     UNION
     SELECT     
         CONVERT(NVARCHAR(6), DATEADD(MONTH, - 2, MIN(SNAPDATE)), 112) AS PERI, 
         MIN(YEAR) AS ANNE, 
         MIN(MONTH) AS MOIS
     FROM         
         dbo.SALES_Daily) AS T2 ON T2.ANNE = T1.ANNEE AND T2.MOIS = T1.MOIS  
INNER JOIN
    csk.Data_Invc AS T3 ON CONVERT(NVARCHAR(6), T3.SNAP, 112) = T2.PERI
GROUP BY 
    T1.SNAP

1 个答案:

答案 0 :(得分:0)

这未经测试,但我认为这可能会给您带来真正的帮助。如果我离基地很远,那么我道歉。如果没有样本数据,我可以在黑暗中进行射击。

; WITH cte AS 
    (
        SELECT     
             CONVERT(NVARCHAR(6), PERI) AS PERI, 
             YEAR(SNAP) AS ANNE, 
             MONTH(SNAP) AS MOIS
         FROM          
             stg.sales
         WHERE      
             (DAY(SNAP) = 1)
         UNION
         SELECT     
             CONVERT(NVARCHAR(6), DATEADD(MONTH, - 2, MIN(SNAPDATE)), 112) AS PERI, 
             MIN(YEAR) AS ANNE, 
             MIN(MONTH) AS MOIS
         FROM         
             dbo.SALES_Daily
    )
, Anothercte AS 
    (
        SELECT
            CONVERT(NVARCHAR(6), SNAP, 112) As ConvSNAP
            , INVC
        FROM 
            csk.Data_Invc
    )
SELECT 
    s.SNAP, SUM(di.INVC) AS INV2
FROM
    stg.sales AS s
INNER JOIN
    cte ON cte.ANNE = s.ANNEE AND cte.MOIS = s.MOIS  
INNER JOIN
    Anothercte AS di ON di.ConvSNAP = cte.PERI
GROUP BY 
    s.SNAP