我基本上有一个我创建的事务表,用于记录和输出发票。 我有一个销售标志(= 1)和购买(= 2)。
我想要一个简单的SQL来按月计算销售和购买量。 问题是,如果我从组中删除事务类型(mybooks_trans_class_id_fk)它不起作用,但是如果我把它留在结果中则不是我想要的。
SQL:
SELECT
DATEPART(Year, mybooks_trans_transaction_datetime) as 'sales_year',
DATEPART(Month, mybooks_trans_transaction_datetime) as 'sales_month',
case
when cast( mybooks_trans_class_id_fk as nvarchar(100))!='1' then cast(sum(mybooks_trans_gross_amount) as nvarchar(100))
else '0'
end as total_sales,
case
when cast( mybooks_trans_class_id_fk as nvarchar(100))!='2' then cast(sum(mybooks_trans_gross_amount) as nvarchar(100))
else '0'
end as total_purchases
from view_mybooks_transactions_all_details
GROUP BY DATEPART(Year, mybooks_trans_transaction_datetime),
DATEPART(MM, mybooks_trans_transaction_datetime),mybooks_trans_class_id_fk
结果是:
2012 11 0 15300.00
2012 12 0 2500.00
2013 1 0 1300.00
2013 1 600.00 0
2013 2 0 2750.00
2013 2 1500.00 0
但我希望第1个月只能在一行中,所以我想要的结果是
2012 11 0 15300.00
2012 12 0 2500.00
2013 1 600.00 1300.00
2013 2 1500.00 2750.00
有什么建议吗?我的sql能力最好是适度的!
答案 0 :(得分:2)
这应该有效:(尽量不要改变太多)
SELECT
DATEPART(Year, mybooks_trans_transaction_datetime) as 'sales_year',
DATEPART(Month, mybooks_trans_transaction_datetime) as 'sales_month',
SUM(case
when mybooks_trans_class_id_fk != 1
then mybooks_trans_gross_amount
else 0
end) as total_sales,
SUM(case
when mybooks_trans_class_id_fk != 2
then mybooks_trans_gross_amount
else 0
end) as total_purchases
FROM view_mybooks_transactions_all_details
GROUP BY DATEPART(Year, mybooks_trans_transaction_datetime),
DATEPART(MM, mybooks_trans_transaction_datetime)