我基本上有一个我创建的记录进出发票的交易表。我有一个销售 (=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能力充其量是中等!