mysql left join不返回所有行

时间:2014-08-05 07:09:44

标签: sql-server sql-server-2012

我正在尝试使用brd_day表(此表包含一年中的所有日期)和brr_transactions(所有事务都在此表中)和BRR_ACCOUNT_HIERARCHIES(帐户)来显示sql查询以显示该月的所有日期详情)。

我的查询目前只显示当月有交易的行,但我试图显示当月的所有行,即使一天没有交易。

这是我的代码:

SQL代码:

select dy.day_date,
       SUM(ISNULL(CASE BRR_TRANSACTIONS.SIDE WHEN 'CASHBOOK' THEN AMOUNT END, 0)) "Q_LINK",
       SUM(ISNULL(CASE BRR_TRANSACTIONS.SIDE WHEN 'STATEMENT' THEN AMOUNT END, 0)) "ZEUS_DBT010",
       sum(ISNULL(CASE BRR_TRANSACTIONS.SIDE WHEN 'CASHBOOK' THEN AMOUNT END, 0)) - 
       sum(ISNULL(CASE BRR_TRANSACTIONS.SIDE WHEN 'STATEMENT' THEN AMOUNT END, 0)) "Difference"
from   BRD_DAY dy
       left join brr_transactions on brr_transactions.transaction_date = dy.day_date
                                     and dy.DAY_DATE >= convert(datetime, '20140601', 112) 
                                     and dy.DAY_DATE <= convert(datetime, '20140630', 112)
       inner join BRR_ACCOUNT_HIERARCHIES on brr_transactions.account_id = BRR_ACCOUNT_HIERARCHIES.ACCOUNT_ID
                                             and BRR_ACCOUNT_HIERARCHIES.ACCOUNT_ID = 1911
GROUP by dy.day_date

结果:

Day_date                   q_link           zeus_dbt             difference 
2014-06-02 00:00:00.000 25560.330000      0.000000            25560.330000
2014-06-03 00:00:00.000 129292.860000     0.000000            129292.860000
2014-06-04 00:00:00.000 0.000000          10966.840000       -10966.840000
2014-06-05 00:00:00.000 0.000000          26742.060000       -26742.060000
2014-06-06 00:00:00.000 26883.480000      26883.480000        0.000000
2014-06-09 00:00:00.000 1305.730000       1305.700000         0.030000
2014-06-10 00:00:00.000 7104.150000       7104.150000         0.000000
2014-06-11 00:00:00.000 1080.270000       0.000000            1080.270000
2014-06-12 00:00:00.000 2929.600000       0.000000           2929.600000           
2014-06-13 00:00:00.000 342047.930000     0.000000            342047.930000

提前致谢

2 个答案:

答案 0 :(得分:2)

您应该同时进行两个联接left联接,或者您应该在inner加入之前逻辑地将left联接到右侧表格,如下所示:

select dy.day_date,
   SUM(ISNULL(CASE tr.SIDE WHEN 'CASHBOOK' THEN AMOUNT END, 0)) "Q_LINK",
   SUM(ISNULL(CASE tr.SIDE WHEN 'STATEMENT' THEN AMOUNT END, 0)) "ZEUS_DBT010",
   sum(ISNULL(CASE tr.SIDE WHEN 'CASHBOOK' THEN AMOUNT END, 0)) - 
   sum(ISNULL(CASE tr.SIDE WHEN 'STATEMENT' THEN AMOUNT END, 0)) "Difference"
from   BRD_DAY dy
   left join brr_transactions tr
   inner join BRR_ACCOUNT_HIERARCHIES ach
       on tr.account_id = ach.ACCOUNT_ID
          and ach.ACCOUNT_ID = 1911
       on tr.transaction_date = dy.day_date
where
     dy.DAY_DATE >= convert(datetime, '20140601', 112) 
     and dy.DAY_DATE <= convert(datetime, '20140630', 112)

我还将最后两个条件(仅在dy)下移到WHERE子句中,因为我认为它们应用于整个查询,而不仅仅是作为连接条件。

答案 1 :(得分:0)

让你的第二次加入也是左连接。现在你告诉sql server通过那些有层次结构链接的记录过滤你的dy + tran结果。