1

我有两个表l & C,它们由两个字段链接,l.mIDcc.mID表包含三种类型的记录cs, ls, & vs,我的查询需要从 l 中选择所有记录,作为查询的一部分,有三列显示总计cs, ls & vs

到目前为止,我正在使用外部联接:

SELECT l.*, COUNT(*) FROM l LEFT OUTER JOIN c ON c.mID = l.mID WHERE l.mID = 2

但这只是在一列中附加了一个完整的总数,任何帮助都会非常感谢。

4

2 回答 2

2

您可以在计数中使用CASE语句:

select
  l.*
  ,COUNT(CASE WHEN c.type = 'cs' then 1 END) as cscount
  ,COUNT(CASE WHEN c.type = 'ls' then 1 END) as lscount
  ,COUNT(CASE WHEN c.type = 'vs' then 1 END) as vscount
from l
left outer join c on c.mID = l.mID
where l.mID = 2
于 2012-07-24T15:13:17.070 回答
1
select
  l.*
  ,sum(c.type = 'cs') as cscount
  ,sum(c.type = 'ls') as lscount
  ,sum(c.type = 'vs') as vscount
from l
left outer join c on c.mID = l.mID
where l.mID = 2
于 2012-07-24T15:16:56.807 回答