SQL COUNT()/ LEFT JOIN?

前端之家收集整理的这篇文章主要介绍了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
原文链接:https://www.f2er.com/mssql/79122.html

猜你在找的MsSQL相关文章