1

您好,我有以下格式的两个表格:

一张桌子:

  ID   |  columnx | event |
  1    |     4    | call  |
  2    |     7    | call  |
  3    |     4    | call  |
  4    |     11   | visit |

B 表:

columnx  | fName |
  4      | clare |
  7      | Bill  |
  9      | Tom   |
  11     | Nick  |

我做了如下查询:

Select A.columnx ,B.fName,Count(event) as Calls
from A
Left Join B on A.columnx = B.columnx 
where 'event' LIKE 'call';

它给出的输出如下:

 columnx | fname  | Calls|
    4     | Clare  |   2  |
    7     | Bill   |   1  |
    11    | Nick   |   0  |

但是我怎样才能得到以下输出:

 columnx  | fname  | Calls|
    4     | Clare  |   2  |
    7     | Bill   |   1  |
    11    | Nick   |   0  |
    9     | Tom    |   0  |

我的意思是当一个特定的记录没有被加入时,我仍然需要选择计数为 0 的记录。这可以通过加入来完成,还是我需要找到另一种方式。有什么建议么。谢谢你。

4

2 回答 2

0

将 'event' LIKE 'call' 移动到左连接的附加条件

    Select B.columnx ,B.fName ,Count(A.'event') as Calls
    from A
    Right Join B on A.columnx   = B.columnx   and A.'event' LIKE 'call'
    group by B.columnx  ,B.fName 
    order by B.columnx   
于 2013-02-14T17:35:54.840 回答
0

您可以使用子查询来获取count()调用:

select dv.columnx,
  dv.fname,
  coalesce(dl.calls, 0) Calls
from device dv
left join
(
  select count(dl.event) Calls, dl.columnx
  from deal dl
  where dl.event LIKE 'call'
  group by dl.columnx
) dl
  on dv.columnx = dl.columnx

请参阅SQL Fiddle with Demo

或者,这可以通过将WHERE过滤器移动到以下位置来完成,而无需子查询JOIN

select dv.columnx,
  dv.fname,
  coalesce(count(dl.event), 0) Calls
from device dv
left join deal dl
  on dv.columnx = dl.columnx
  and dl.event LIKE 'call'
group by dv.columnx,  dv.fname

请参阅带有演示的 SQL Fiddle

这将返回:

| COLUMNX | FNAME | CALLS |
---------------------------
|       4 | clare |     2 |
|       7 |  Bill |     1 |
|       9 |   Tom |     0 |
|      11 |  Nick |     0 |
于 2013-02-14T17:43:16.893 回答