我有一个客户端表,我需要按以下顺序选择数据:
Gender Count
-----------------
Female 10
Male 50
Unknown 2
(上表数据仅作为示例)
为实现这一目标,我使用了以下SQL:
SELECT decode(gender, 'F', 'Female', 'M', 'Male', 'Unknown') "Gender"
, count(ID) "Count"
FROM client c
WHERE c.created <= '01-JAN-2000'
GROUP BY decode(gender, 'F', 'Female', 'M', 'Male', 'Unknown')
ORDER BY decode(gender, 'F', 'Female', 'M', 'Male', 'Unknown')
;
但是,问题是在1-JAN-2000之前没有创建客户端!因此,该表显示为空白:
Gender Count
----------------
但是,我想在这种情况下表明:
Gender Count
----------------
Female 0
Male 0
Unknown 0
请告诉我该怎么做?
答案 0 :(得分:4)
您可以从性别上选择(使用内联视图)开始,然后对结果执行left outer join
。这将保证在第一列中始终显示可用的性别列表:
SELECT g.gender
, count(ID) "Count"
FROM ( select 'Female' gender from dual
union all
select 'Male' gender from dual
union all
select 'Unknown' gender from dual
) g
left
outer
join client c
on decode(c.gender, 'F', 'Female', 'M', 'Male', 'Unknown') = g.gender
and c.created <= '01-JAN-2000'
GROUP
BY g.gender
ORDER
BY g.gender
;
答案 1 :(得分:2)
您应该规范化数据以保存性别表。或至少在您的查询中使用一个(视图),如下所示,并进行OUTER连接。
并使用标准日期格式..
编辑:为了更好的可读性和性能,您必须仔细分类性别。这里假设一个额外的类别'U'用于未知案例。
SELECT g.GENDER "Gender"
, count(ID) "Count"
FROM client c,
( SELECT 'Female' As Gender,'F' as GenderId FROM DUAL
UNION ALL
SELECT 'Male','M' FROM DUAL
UNION ALL
SELECT 'Unknown','U' FROM DUAL
) g
WHERE c.created(+) <= DATE '2000-01-01'
AND c.Gender(+) = g.genderId
GROUP BY g.gender
ORDER BY g.gender
;
答案 2 :(得分:0)
这是怎么做的
SELECT
'Female' Gender
, Count(c.ID) Count
FROM
Client c
WHERE
c.Gender = 'F'
UNION ALL
SELECT
'Male' Gender
, Count(c.ID) Count
FROM
Client c
WHERE
c.Gender = 'M'
UNION ALL
SELECT
'Unknown' Gender
, Count(c.ID) Count
FROM
Client c
WHERE
c.Gender is NULL