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,因为它会给我所有的行两次。
惊人的。给我我需要的。非常感谢。 – StarsTurnCold