您好我遇到了SQL问题,我希望答案非常简单。
我有一个具有以下结构的数据库。
State Gender birthyear birthname count
----- ------ --------- --------- ------
AK F 1923 Helen 15
AK F 1926 Helen 35
AK F 1927 Susan 25
AK F 1920 Helen 15
有数千条记录,我希望输出看起来像这样:
birthname 1910 1911 1912 -->2012
----- ------ --------- --------- ------
Helen 5 6 12 800
使用MS Access我能够得到一些结果:
SELECT DISTINCT as1.birthname AS Expr1,
(select totalcount from AK as2 where as1.birthname=as2.birthname and as1.gender=as2.gender and as1.state=as2.state and as1.birthyear=as2.birthyear and birthyear=1910) as 1910,
(select totalcount from AK as2 where as1.birthname=as2.birthname and as1.gender=as2.gender and as1.state=as2.state and as1.birthyear=as2.birthyear and birthyear=1911) as 1911,
(select totalcount from AK as2 where as1.birthname=as2.birthname and as1.gender=as2.gender and as1.state=as2.state and as1.birthyear=as2.birthyear and birthyear=2012) as 2012
FROM AK AS as1
答案 0 :(得分:0)
您应该使用条件聚合执行此操作:
SELECT as1.birthname AS Expr1,
SUM(case when birthyear = 1910 then `count` else 0 end) as yr_1910,
SUM(case when birthyear = 1911 then `count` else 0 end) as yr_1911,
SUM(case when birthyear = 1912 then `count` else 0 end) as yr_1912
FROM AK AS as1
GROUP BY as1.birthname;
我不确定gender
和state
的位置。这些不包含在外部查询中,这可能是导致语法错误的原因。您可能希望将这些包含在聚合中:
SELECT as1.birthname, as1.gender, as1.state,
SUM(case when birthyear = 1910 then `count` else 0 end) as yr_1910,
SUM(case when birthyear = 1911 then `count` else 0 end) as yr_1911,
SUM(case when birthyear = 1912 then `count` else 0 end) as yr_1912
FROM AK AS as1
GROUP BY as1.birthname, as1.gender, as1.state;
答案 1 :(得分:0)
如果您使用的是Oracle 11g +,则可以使用SQL PIVOT
语法生成交叉表报告。使用示例数据,查询将如下所示:
with sample_data as
(select 'AK' state, 'F' gender, 1923 birthyear, 'Helen' birthname, 15 namecount from dual union all
select 'AK', 'F', 1926, 'Helen', 35 from dual union all
select 'AK', 'F', 1927, 'Susan', 25 from dual union all
select 'AK', 'F', 1920, 'Helen', 15 from dual)
select * from (
select * from sample_data
)
pivot
(
sum(namecount)
for birthyear in (1920,1921,1922,1923,1924,1925,1926,1927,1928,1929,1230)
);
不幸的是,IN
子句中的年份列表必须是硬编码的,您无法使用子查询动态生成该列表。但是,这应该不会太难以初步填充。