明智的两个月收入

时间:2015-09-03 10:15:07

标签: sql sql-server sql-server-2008

我正在尝试获取最近2个月的数据......但查询并没有给出完美的结果....

    SELECT DAY(table_A.PaymentDate) as date1 , 
           (case when MONTH(table_A.PaymentDate) = MONTH(CURRENT_TIMESTAMP) - 1
                 then CAST(SUM(table_A.Total_Amount) AS INT)  
                 else 0  
                 end) AS last_month_CNT, 
           (case when MONTH(table_A.PaymentDate) = MONTH(CURRENT_TIMESTAMP)
                 then CAST(SUM(table_A.Total_Amount) As INT) 
                 else 0  
                 end) as This_month_CNT  
    FROM   Tbl_Pan_Paymentdetails  table_A  
           FULL OUTER JOIN Tbl_Pan_Paymentdetails table_B 
                       ON table_A.PaymentDate=table_B.PaymentDate 
    WHERE  YEAR(table_A.PaymentDate) = YEAR(CURRENT_TIMESTAMP)
           AND
           table_A.PaymentDate >= DATEADD(MONTH, -1, GETDATE())  
   GROUP BY 
           DAY(table_A.PaymentDate) ,MONTH(table_A.PaymentDate) 
   order by 
           DAY(table_A.PaymentDate);

1 个答案:

答案 0 :(得分:1)

将整个案例表达式移到sum函数中,并且不要在group by中包含月份。此外,完全外连接似乎是不必要的,所以我删除它。

这应该是你要找的东西:

SELECT 
  DAY(PaymentDate) as date1 ,
  SUM(CASE WHEN MONTH(PaymentDate) = MONTH(CURRENT_TIMESTAMP)-1 THEN CAST(Total_Amount AS INT) ELSE 0  END) AS last_month_CNT,
  SUM(CASE WHEN MONTH(PaymentDate) = MONTH(CURRENT_TIMESTAMP)   THEN CAST(Total_Amount AS INT) ELSE 0  END) AS This_month_CNT 
FROM Tbl_Pan_Paymentdetails  
WHERE YEAR(PaymentDate) = YEAR(CURRENT_TIMESTAMP)
  AND PaymentDate >= DATEADD(MONTH, -1, GETDATE()) 
GROUP BY  DAY(PaymentDate)
ORDER BY  DAY(PaymentDate);