3

我是一个相对的 SQL 初学者,我不完全确定如何问我在问什么(所以我也不完全确定如何搜索它的帮助)。

我想使用一个SELECT语句,该语句使用GROUP BY子句按某个属性进行分组,同时引用该组选择的行。有没有办法做到这一点?(我使用的是 FWIW、SQLite3,但我认为这更多是通用 SQL 语法的问题。)

我有一张表格population,里面有关于人和家庭的数据。每排是一个人,每个人都被分成从一到十几个的家庭。

每户一人(一般为第一人,by uid)为户主,并有head列集。我想要GROUP BYhousehold_id,并且还选择uid组中每个成员的“头”。有没有办法用一个语句来做到这一点?

这是我所拥有的:

SELECT DISTINCT household_id,
    COUNT(uid) AS members   /* The number of members in each household; it works */,
    (SELECT uid FROM "group" WHERE head == 1) /* Only I don't know how to do this */
    FROM population GROUP BY household_id;

我尝试了这样的事情,但它没有给我想要的东西:

SELECT DISTINCT household_id,
    COUNT(uid) AS members,
    (SELECT uid FROM population WHERE household_id == household_id AND head == 1) /* <-- here */
    FROM population GROUP BY household_id;

但这当然会选择第一行household_idhousehold_id; 即表中的第一行。我如何仅引用该特定组中的household_id那个?DISTINCT

有小费吗?提前致谢。

4

2 回答 2

4

试试这个,

SELECT  household_id,
        COUNT(uid) AS members, 
        MAX(CASE WHEN head = 1 THEN uid ELSE NULL END) headID
FROM    population 
GROUP   BY household_id;
于 2013-02-28T17:05:19.830 回答
1

你本可以走在正确的轨道上

SELECT DISTINCT household_id,
COUNT(uid) AS members,
(SELECT uid FROM population WHERE household_id == household_id AND head == 1) /* <-- here */
FROM population GROUP BY household_id;

但是您需要为人口表起别名,因为它在查询中使用了两次。

SELECT DISTINCT household_id,
COUNT(uid) AS members,
(SELECT uid FROM population gr_head WHERE pop.household_id = gr_head.household_id AND head == 1) /* <-- here */
FROM population pop GROUP BY household_id;
于 2013-02-28T17:08:34.347 回答