我有一张桌子,例如人物类型的人(私人,公共,政府,商人,失业)。类型可以为null或Empty。我在没有主表的Person表中保存类型值。我想根据类型是否存在来选择具有计数的所有分组类型。 我知道这有点奇怪,但要求是这样的。以下是脚本:
CREATE TABLE [Persons](
[ID] [int] IDENTITY(1,1) NOT NULL,
[FULLNAME] [varchar](50) NULL,
[TYPE] [varchar](10) NULL
) ON [PRIMARY]
INSERT INTO Persons(FULLNAME,[TYPE]) VALUES('ABD', 'Private');
INSERT INTO Persons(FULLNAME,[TYPE]) VALUES('DEF', 'Government');
INSERT INTO Persons(FULLNAME,[TYPE]) VALUES('DEF', 'Jobless');
结果应如下所示:
TYPE COUNT
Private 1
Public 0
Government 1
Businessman 0
Jobless 1
答案 0 :(得分:2)
您可以使用with
子句创建所有可能类型的公用表表达式(CTE),并将其与人员表连接起来。
with types (type)
as (
select 'Private' from dual
union all
select 'Public' from dual
union all
select 'Government' from dual
union all
select 'Businessman' from dual
union all
select 'Jobless' from dual
)
select t.type,
count(p.type) "COUNT"
from types t
left outer join Persons p on t.type = p.type
group by t.type;
答案 1 :(得分:1)
如果你使用MS Sql Server而不是Oracle(作为你的DDL的语法建议):
select all_types.type, count(distinct persons.id) from (
select 'Private' as type union all
select 'Public' union all
select 'Government' union all
select 'Businessman' union all
select 'Jobless'
) all_types left outer join Persons on (all_types.type=persons.type)
group by all_types.type;