我有这个查询来计算销售库存的月到日数量。它工作正常:
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列旁边找到名为“YTD Sales”的第二列(WHERE条件为2017-01-01至2017-03-31)。我如何同时获得1个查询?我试过这样的东西,但它没有用,它只给了我全部0的MTD和YTD。我确定我做错了什么:
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,因为它会给我两次所有的行。
答案 0 :(得分: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]