the*_*ner 8 sql t-sql count left-join
我有三个表:呼叫,附件和备注,我想显示呼叫表中的所有内容,还显示呼叫是否有附件以及呼叫是否有备注. - 通过确定是否存在带有call_id的附件或注释记录.可能有笔记和附件,或者可能没有,但我需要知道.
表结构:
要求:
call_id | title | description
Run Code Online (Sandbox Code Playgroud)
附件:
attach_id | attach_name | call_id
Run Code Online (Sandbox Code Playgroud)
笔记:
note_id | note_text | call_id
Run Code Online (Sandbox Code Playgroud)
如果我写:
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
, title
, description
Run Code Online (Sandbox Code Playgroud)
给我一个所有电话和附件数量的列表.
如何添加包含注释数量的列或指示有注释的列?
有任何想法吗?
谢谢.
Mar*_*ith 18
SELECT
c.call_id,
title,
description,
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,title,description
Run Code Online (Sandbox Code Playgroud)
SELECT
c.call_id,
title,
description,
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,title,description
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20445 次 |
| 最近记录: |