返回前一个月的6个上个月的选择

时间:2019-06-20 06:47:09

标签: sql-server

SELECT DISTINCT itemcode, 
                itemdescription, 
                unitofmeasure, 
                Sum([current]) AS [Ending Balance] 
WHERE  transactiondate >= Dateadd(month, Datediff(month, 0, 
                                         Dateadd(m, -6, '2019-01-31' 
                                         )), 0) 

1 个答案:

答案 0 :(得分:1)

您的代码缺少FROM和GROUP BY子句,可以按以下脚本所示计算Date Diff(6 Mont考虑结束日期='2019-01-31')-

SELECT
itemcode, 
itemdescription, 
unitofmeasure, 
Sum([current]) AS [Ending Balance] 
FROM <your_table> -- FROM is missing. Please add appropriate table name
WHERE  transactiondate Between 
    DATEADD(month, -6, '2019-01-31') 
    AND '2019-01-31'  
GROUP BY itemcode,itemdescription,unitofmeasure
-- GROUP BY is required as you applied Aggregation on column [current]

如果您只想获取前6个月的记录,则WHERE条件如下-

WHERE  YEAR(transactiondate) = YEAR(DATEADD(month, -6, '2019-01-31'))
AND MONTH(transactiondate) = MONTH(DATEADD(month, -6, '2019-01-31')) 

要获取最近6个月的结果,WHERE如下-

WHERE transactiondate BETWEEN
CAST(LEFT(CAST(DATEADD(MM,-6,CAST('2019-01-31' AS DATE)) AS VARCHAR),7) + '-01' AS DATE)
AND
DATEADD(DD,-1,CAST(CAST(LEFT(CAST(CAST('2019-01-31' AS DATE) AS VARCHAR),7) + '-01' AS DATE) AS DATE))
-- This is basically: transactiondate BETWEEN '2018-07-01' AND '2018-12-31'