SQL COUNT()/ LEFT JOIN?

我有三个表:呼叫,附件和备注,我想显示呼叫表中的所有内容,还显示呼叫是否有附件以及呼叫是否有备注. – 通过确定是否存在带有call_id的附件或注释记录.可能有笔记和附件,或者可能没有,但我需要知道.

表结构:

要求:

call_id  |  title  |  description

附件:

attach_id  |  attach_name  |  call_id

笔记:

note_id  |  note_text  |  call_id

如果我写:

SELECT c.call_id,title,description,count(attach_id) 
FROM calls c 
LEFT JOIN attachments a ON c.call_id = a.call_id 
GROUP BY c.call_id,description

给我一个所有电话和附件数量的列表.

如何添加包含注释数量的列或指示有注释的列?

有任何想法吗?

谢谢.

解决方法

为了计数
SELECT 
     c.call_id,count(disTINCT attach_id) AS attachment_count,count(disTINCT note_id)  AS notes_count 
FROM calls c 
LEFT JOIN attachments a ON c.call_id = a.call_id 
LEFT JOIN notes n ON n.call_id = c.call_id 
GROUP BY c.call_id,description

或者存在(如果这是你需要的话会更有效率)

SELECT 
     c.call_id,count(attach_id) AS attachment_count,case
        when exists (select * from notes n WHERE n.call_id = c.call_id) then
            cast(1 as bit)
        else
            cast(0 as bit)
    end as notes_exist
FROM calls c 
LEFT JOIN attachments a ON c.call_id = a.call_id 
GROUP BY c.call_id,description

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...