以下是包含表es_preadmission
的示例数据的模式 admno |pre_gender|pre_class| pre_scat_id |bpl |sgc |handi|ser_cat
---------|----------|---------|-------------|----|----|-----|--------
1 |Male |1 |GEN |no |no |no |1
2 |Male |1 |GEN |no |no |no |1
3 |Male |1 |GEN |bpl |no |no |1
4 |Female |2 |GEN |no |sgc |no |1
5 |Male |1 |SC |no |no |no |1
6 |Female |1 |GEN |no |no |no |1
7 |Female |2 |GEN |no |no |no |5
8 |Male |2 |GEN |bpl |no |no |1
9 |Male |2 |ST |no |no |no |1
10 |Male |1 |OBC |no |no |no |3
11 |Female |1 |ST |no |no |no |5
12 |Male |2 |GEN |no |no |no |1
13 |Male |2 |SC |no |no |PH |1
14 |Female |2 |SC |bpl |no |no |1
15 |Female |1 |GEN |no |no |no |2
**我正在尝试从每个类别(GEN,SC,ST,OBC),bpl,sgc,handi,ser_cat类明智地获得男女学生的数量。实施例
1 2
M F M F
GEN 20 9 25 10
SC 5 2 9 4
ST 0 3 0 0
OBC 1 2 1 0
PH 0 0 1 0
BPL 2 3 7 2
** 现在我要尝试上面这些数字 -
SELECT pre_scat_id AS cat, pre_gender, COUNT(admno)
FROM es_preadmission
WHERE pre_scat_id IN ('GEN','SC','ST','OBC')
GROUP BY pre_scat_id, pre_gender
UNION ALL
SELECT pre_handi AS cat, pre_gender, COUNT(admno)
FROM es_preadmission
WHERE pre_handi = 'Yes' OR pre_handi = 'No'
GROUP BY pre_handi, pre_gender
UNION ALL
SELECT pre_bpl AS cat, pre_gender, COUNT(admno)
FROM es_preadmission
WHERE pre_bpl = 'Yes' OR pre_bpl ='No'
GROUP BY pre_bpl, pre_gender;
但我没有得到理想的输出。以下输出基于上述查询在实际数据库上绘制。
cat|pre_gender|COUNT(admno)
GEN| Female |216
GEN| Male |371
OBC| Female |30
OBC| Male |50
SC | Female |36
SC | Male |65
ST | Male |9
No | Female |281
No | Male |495
PH | Male |1
No | Female |268
No | Male |467
bpl| Female |13
bpl| Male |25
需要帮助如何明智地获得输出类
答案 0 :(得分:1)
您需要汇总不同的CASE,例如对于第一个SELECT:
SELECT pre_scat_id AS cat
, COUNT(CASE WHEN pre_gender = 'Male' AND pre_class = 1 THEN 1 END) AS M1
, COUNT(CASE WHEN pre_gender = 'Female' AND pre_class = 1 THEN 1 END) AS F1
, COUNT(CASE WHEN pre_gender = 'Male' AND pre_class = 2 THEN 1 END) AS M2
, COUNT(CASE WHEN pre_gender = 'Female' AND pre_class = 2 THEN 1 END) AS F2
FROM es_preadmission
WHERE pre_scat_id IN ('GEN','SC','ST','OBC')
GROUP BY pre_scat_id