MS SQL分组在Date字段上有两个表

时间:2017-03-06 08:25:12

标签: sql-server grouping

我正在尝试从两个通过数据字段连接的表中分组和检索数据。两个表格的输出均为年份和月份。 当我与另一个表“purch_ret_hd”进行联接时,结果对于Purchase_Return列不正确。如果查询中出现问题,请提出建议

Select YEAR(grn_hd.grn_date) AS GRN_Date,    
       DATENAME(MONTH,grn_hd.grn_date) AS Month_Name, 
       Month(grn_hd.grn_date) AS Month,     
       SUM(grn_hd.inv_amt) AS Purchase_Gross,  
       SUM(grn_hd.disc_amt) AS Purchase_discount,   
       SUM(grn_hd.inv_amt) - SUM(grn_hd.disc_amt) AS 
       Purchase_After_Discount,     
       sum(grn_hd.net_amt) AS Purchase_Net,   
       SUM(purch_ret_hd.net_amt) AS Purchase_Return 
FROM grn_hd   
LEFT JOIN purch_ret_hd
ON YEAR(purch_ret_hd.entry_date) = YEAR(grn_hd.grn_date) AND 
Month(purch_ret_hd.entry_date) = Month(grn_hd.grn_date)
AND purch_ret_hd.loc_id = grn_hd.loc_id 
AND purch_ret_hd.loc_id = grn_hd.loc_id 
GROUP BY     
YEAR(grn_hd.grn_date),Month(grn_hd.grn_date),
DATENAME(MONTH,grn_hd.grn_date)
Order by 1,3

1 个答案:

答案 0 :(得分:0)

请注意,“DATENAME(MONTH,grn_hd.grn_date)”列为Month_Name“两次,但第一个未正确写入(” eATENAME (MONTH,grn_hd.grn_date)AS MONTH_NAME“)