我有4列的下表:
id,familyId,memberType,memberName
=================================
1, 1, main, RBV
2, 1, spouse, VBD
3, 1, child, CDE
4, 2, spouse, OLL
5, 2, sibling, HAQ
6, 3, main, OOM
7, 3, sibling, NBB
8, 3, child, SSS
使用这些数据,我如何编写一个查询来获取每个家庭成员的数量以及该家庭是否有主?
这就是我需要的:
familyId,count,hasMain
=====================
1, 3, 1
2, 2, 0
3, 3, 1
我知道group by familyId
会给我每个家庭成员的数量。但它并没有给我这个家庭是否有主要内容。也许这不能在单个查询中实现。
答案 0 :(得分:3)
您需要使用汇总函数COUNT()
来计算基于familyID
和MAX()
和CASE
语句的所有行,以检查membertype
列是否包含主:
SELECT familyID,
COUNT(*) AS "Count",
MAX(CASE WHEN memberType = 'main' THEN 1 ELSE 0 END) AS hasMain
FROM TableName
GROUP BY familyID
答案 1 :(得分:0)
使用条件聚合和GROUP BY
:
SELECT
familyId,
COUNT(*) AS family_cnt,
CASE WHEN SUM(CASE WHEN memberType = 'main' THEN 1 ELSE 0 END) > 0
THEN 1 ELSE 0 END AS hasMain
FROM
yourTable
GROUP BY
familyId;
答案 2 :(得分:0)
这是一种方法:
SQL> with test (id, familyid, membertype) as
2 (select 1, 1, 'main' from dual union
3 select 2, 1, 'spouse' from dual union
4 select 3, 1, 'child' from dual union
5 select 4, 2, 'spouse' from dual union
6 select 5, 2, 'sibling' from dual union
7 select 6, 3, 'main' from dual union
8 select 7, 3, 'sibling' from dual union
9 select 8, 3, 'child' from dual
10 ),
11 hm as
12 (select familyid
13 from test
14 where membertype = 'main'
15 )
16 select t.familyid,
17 count(*) cnt,
18 decode(hm.familyid, null, 0, 1) hasmain
19 from test t
20 left join hm on hm.familyid = t.familyid
21 group by t.familyid, decode(hm.familyid, null, 0, 1)
22 order by t.familyid;
FAMILYID CNT HASMAIN
---------- ---------- ----------
1 3 1
2 2 0
3 3 1
SQL>
答案 3 :(得分:0)
你也可以试试这个,
SELECT familyid, count(1) count_, MAX(DECODE(membertype, 'main', 1, 0)) has_main
FROM test
GROUP BY familyid;