1

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

4

1 回答 1

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)
于 2013-02-08T16:25:09.427 回答