2017-04-13 36 views
0

我有这个查询来计算出售的库存月份数量。它工作正常:如何在1个SQL查询中获取具有不同条件的2列?

SELECT customer.customer_name as 'Customer', item_id as 'Item ID', item_desc              
AS 'Description', unit_price AS 'Cost', COALESCE(sum(qty_shipped), 0) as 'MTD Sales' 
FROM p21_sales_history_report_view   
JOIN customer on customer.customer_id = p21_sales_history_report_view.corp_address_id 
WHERE invoice_date between CAST('2017-03-01' as date) and CAST('2017-03-31' as date) 
GROUP BY customer.customer_name, item_desc, item_id, unit_price 
ORDER BY customer.customer_name, item_desc 

不过,我也想名为“YTD销售”第二列(与2017年1月1日至2017年3月31日WHERE条件)旁边的MTD列。我怎样才能在1个查询中获得?我尝试过这样的事情,但没有奏效,它只是给了我所有的MTD和YTD 0。我敢肯定我做错了事:

SELECT customer.customer_name as 'Customer', item_id as 'Item ID', 
item_desc as 'Description', unit_price as 'Cost', 
COALESCE(sales_cost, 0) as 'Cost of Sales', 
SUM(CASE WHEN invoice_date BETWEEN CAST('2017-03-01' as date) and CAST('2017-03-31' as date) 
THEN COALESCE(qty_shipped,0) ELSE 0 END) as 'MTD Sales', 
SUM(CASE WHEN invoice_date between CAST('2017-01-01' as date) and CAST('2017-03-31' as date) 
THEN COALESCE(qty_shipped,0) Else 0 END) as 'YTD Sales' 
FROM p21_sales_history_report_view 
JOIN customer ON customer.customer_id = p21_sales_history_report_view.corp_address_id 
GROUP BY item_desc, item_id, customer.customer_name, unit_price, 
p21_sales_history_report_view.invoice_date, sales_cost 
ORDER BY customer.customer_name, item_desc 

有什么建议吗?显然,我不能使用UNION,因为它会给我所有的行两次。

回答

1

这看起来是正确的 - 我会添加一个列SUM(COALESCE(qty_shipped,0))以确保您确实总结了所有内容。我猜你的连接有问题。

你也可以做到这一点通过内部联接两个子查询

select * 
from 

(SELECT customer.customer_name as 'Customer', item_id as 'Item ID', item_desc              
    AS 'Description', unit_price AS 'Cost', COALESCE(sum(qty_shipped), 0) as 'MTD Sales' 
    FROM p21_sales_history_report_view   
    JOIN customer on customer.customer_id = p21_sales_history_report_view.corp_address_id 
    WHERE invoice_date between CAST('2017-03-01' as date) and CAST('2017-03-31' as date) 
    GROUP BY customer.customer_name, item_desc, item_id, unit_price 
    ORDER BY customer.customer_name, item_desc) MTD 
inner join 
(SELECT customer.customer_name as 'Customer', item_id as 'Item ID', item_desc              
    AS 'Description', unit_price AS 'Cost', COALESCE(sum(qty_shipped), 0) as 'YTD Sales' 
    FROM p21_sales_history_report_view   
    JOIN customer on customer.customer_id = p21_sales_history_report_view.corp_address_id 
    WHERE invoice_date between CAST('2017-01-01' as date) and CAST('2017-03-31' as date) 
    GROUP BY customer.customer_name, item_desc, item_id, unit_price 
    ORDER BY customer.customer_name, item_desc) YTD 
on MTD.Customer = YTD.Customer 
and mtd.[Item ID] = YTD.[Item ID] 
+0

惊人的。给我我需要的。非常感谢。 – StarsTurnCold

相关问题