我有一张桌子attendance
+-----------------------------------------------+
+ p_id | day_1 | day_2 | day_3 | day_4 | day_5 |
+-----------------------------------------------+
+ 1 | P | P | P | A | A |
+ 2 | P | A | A | P | P |
+ 3 | A | A | P | P | P |
+-----------------------------------------------+
这里p_id
= people.id
外键
还有一个表people
+------------+
+ id | gend|
+------------+
| 1 | M |
| 2 | F |
| 3 | M |
+------------+
我想要得到这样的最终输出,其中包含缺席总人数及其各自的男性/女性人数:
+---------------------------------------+
+ day | total_a | males | females +
+---------------------------------------+
+ day_1 | 1 | 1 | 0 +
+ day_2 | 2 | 1 | 1 +
+ day_3 | 1 | 0 | 1 +
以此类推
我不知道从哪里开始这样的查询。任何帮助表示赞赏。
答案 0 :(得分:0)
这听起来像您需要先取消attendance
表的透视,然后join
并重新聚合:
select a.day, sum(a.pa = 'P') as total,
sum(a.pa = 'P' and p.gend = 'M') as num_males,
sum(a.pa = 'P' and p.gend = 'F') as num_females
from ((select p_id, day_1 as pa, 'day_1' as day
from attendance a
) union all
(select p_id, day_2, 'day_2' as day
from attendance a
) union all
(select p_id, day_3, 'day_3' as day
from attendance a
) union all
(select p_id, day_4, 'day_4' as day
from attendance a
) union all
(select p_id, day_5, 'day_5' as day
from attendance a
)
) a join
people p
on p.id = a.p_id
group by day
order by day;