如果condition为0,则SQL Count无结果

时间:2017-07-05 04:43:37

标签: sql join

我的代码是关于显示正确的结果,其中在另一个具有相同列值

的表中计数

我的数据库:

Clientgroup表

id | clientgroup_name | clientgroup_color
10   Business Customer  green
11   Super VIP          red
12   Ultimate VIP       pink

客户列表:

id | name   | group_id 
1    John      10
2    Mark      10
3    Paul      12
4    Nico      12

我的代码:

SELECT Count(*) as Count,clientgroup_table.clientgroup_name,clientgroup_table.clientgroup_color FROM clientgroup_table, client_list WHERE client_list.group_id = clientgroup_table.id GROUP BY clientgroup_table.clientgroup_name

我的结果:

Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink

我想要的结果:

Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink
0       SUPER VIP           red

我想显示0,即使没有等于它的行

有可能吗?

感谢

4 个答案:

答案 0 :(得分:1)

您当前的查询有两个问题导致输出错误。首先,您使用的是隐式内部联接,它会丢弃不匹配的客户端组表中的记录。相反,您应该使用LEFT JOIN。其次,您正在使用COUNT(*)进行计数,这将为左侧的记录提供一个错误的计数,该记录与右侧的任何内容都不匹配。相反,请使用COUNT(some column from the right)

SELECT
    COUNT(t2.group_id) AS Count,   -- returns 0 if t2.group_id is NULL
    t1.clientgroup_name,
    t1.clientgroup_color
FROM clientgroup_table t1
LEFT JOIN client_list t2
    ON t2.group_id = t1.id
GROUP BY
    t1.clientgroup_name,
    t1.clientgroup_color
ORDER BY
    Count DESC,
    t1.clientgroup_name;

在这里演示:

Rextester

答案 1 :(得分:0)

您可以使用左连接操作来执行此操作以包括没有任何客户端的其他行。 试试这个问题:

SELECT 
  Count(*) as Count,
  clientgroup_table.clientgroup_name,
  clientgroup_table.clientgroup_color 
FROM clientgroup_table left join client_list 
  on client_list.group_id = clientgroup_table.id 
GROUP BY clientgroup_table.clientgroup_name;

答案 2 :(得分:0)

在这种情况下,您可以使用左连接:

SELECT COUNT(*) as Count, clientgroup_name,clientgroup_color FROM client_group 
cg LEFT JOIN client_list cl ON cg.id=cl.group_id GROUP BY 
cg.clientgroup_name,cg.clientgroup_color

答案 3 :(得分:0)

试试这个

if object_id('tempdb..#t1') is not null
drop table #t1
CREATE TABLE #t1
    ([id] int, [clientgroup_name] varchar(17), [clientgroup_color] varchar(5))
;

INSERT INTO #t1
    ([id], [clientgroup_name], [clientgroup_color])
VALUES
    (10, 'Business Customer', 'green'),
    (11, 'Super VIP', 'red'),
    (12, 'Ultimate VIP', 'pink')
;


if object_id('tempdb..#t2') is not null
drop table #t2
CREATE TABLE #t2
    ([id] int, [name] varchar(4), [group_id] int)
;

INSERT INTO #t2
    ([id], [name], [group_id])
VALUES
    (1, 'John', 10),
    (2, 'Mark', 10),
    (3, 'Paul', 12),
    (4, 'Nico', 12)
;

select count(r.group_id) count,t.clientgroup_name,t.clientgroup_color from #t1 t left join #t2 r on r.group_id=t.id
group by t.clientgroup_name,t.clientgroup_color