在联接中使用列函数

时间:2019-06-25 15:38:02

标签: sql

在两个不同的表中,我有包含两个不同收入来源的交易数据。我还有两个表,其中按月汇总了收入。现在,我希望加入两个汇总表(按月),并有一个总收入数字。

select  [table1.transaction_datetime:month] as month, 
sum(table1.revenue1) as revenue1, 
sum(CASE WHEN table2.transaction_amount_sign= '-' 
THEN table2.transaction_amount*-1, 
WHEN  table2.transaction_amount_SIGN='+' 
THEN table2.transaction_amount END)*-1 as revenue2

from        table1
full join   table2

on [table1.transaction_datetime:month] = [table2.postdate_and_posttime:month]

where   table1.transaction_type in ('A','B','C')
    table2.transaction_code in ('X', 'Y', 'ZZ')

group by month
order by month desc

结果比我单独使用的表要高得多。我怀疑我没有适当地加入表和/或列函数在搞砸逻辑。

Table1>>
Month             Revenue1
-----             ---------
2019-06-01         $100,000
2019-05-01          $93,000

Table2>>
Month             Revenue2
-----             ---------
2019-06-01          $45,000
2019-05-01          $37,000

Desired Result>>
Month              Revenue1         Revenue2        Total
-----             ---------        ----------     ---------
2019-06-01         $100,000          $45,000       $145,000
2019-05-01          $93,000          $37,000       $130,000

1 个答案:

答案 0 :(得分:0)

毫无疑问,您每天都有多行,这会导致笛卡尔积。您的return '<a href="' . route('admin.transaction_verified', ['id'=> $row->id, 'tran-id'=> $row->tran_id]) . '" class="btn btn-info btn-rectangle" data-toggle="tooltip" data-original-title="Edit">Send Email</a> 也没有意义,因为full join子句将其变成了where

一种方法是使用inner joinunion all做您想做的事情:

group by