SQL COUNT()/ LEFT JOIN?

时间:2010-12-02 10:49:55

标签: sql tsql 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
       , title
       , description

给我一​​份所有来电和附件数量的清单。

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

有什么想法吗?

感谢。

6 个答案:

答案 0 :(得分: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

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

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

答案 1 :(得分:1)

SELECT c.call_id, title, description, a.call_id, n.call_id
FROM calls c 
LEFT JOIN attachments a ON c.call_id = a.call_id 
LEFT JOIN notes n ON c.call_id = n.call_id
GROUP BY c.call_id,title,description, a.call_id, n.call_id

如果字段4或5中存在呼叫ID,则表示您有附件或备注

如果您需要附上或附注的数量,请查看其他答案,请查看AtaTheDev的帖子。

答案 2 :(得分:0)

在计数中使用distinct

您必须使用不同的计数,因为您的组已经由两个不同的实体增长。所以你必须只计算每个的不同值。下一个查询将返回两个计数以及bit值是否有任何附件和注释。

select
    c.call_id, c.title, c.description,
    count(distinct a.attach_id) as attachments_count,
    count(distinct n.note_id) as notes_count,
    /* add these two if you need to */
    case when count(distinct a.attach_id) > 0 then 1 else 0 end as has_attachments,
    case when count(distinct n.note_id) > 0 then 1 else 0 end as has_notes
from calls c
    left join attachments a
    on (a.call_id = c.call_id)
    left join notes n
    on (n.call_id = c.call_id)
group by c.call_id, c.title, c.description

答案 3 :(得分:0)

我认为它应该是这样的

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

答案 4 :(得分:0)

这也有效:

<style name="TexViewStyle" parent="TextAppearance.AppCompat">
        <item name="android:background">@color/colorPrimaryDark</item>
    </style>

答案 5 :(得分:0)

我使用过这个简单的查询。此查询允许您轻松使用主表列,而无需分组。

   Select StudentName,FatherName,MotherName,DOB,t.count  from Student
   left JOIN
   (
    Select StudentAttendance.StudentID,  count(IsPresent) as count 
    from StudentAttendance
    group by StudentID, IsPresent
   ) as t    
  ON   t.StudentID=Student.StudentID