2014-04-22 81 views
0

您好,我有一個SQL問題,我希望答案很簡單。Oracle數據庫子查詢導致多行

我有一個具有以下結構的數據庫。

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

谷歌搜索「oracle交叉表查詢」將引導您獲取所需的信息。 –

+0

也查找PIVOT – Randy

回答

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; 

我不確定genderstate是否在哪裏。這些不包括在外部查詢中,這可能是您的語法錯誤的原因。您可能要包括這些在聚集:

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; 
+0

如果只有3年,這種方法就沒問題。對於103,根據這個問題,沒有那麼多。 –

+0

@DanBracuk。 。 。對於不同的出生年份,我認爲沒有問題產生103行。我會使用Excel來生成代碼。 –

+0

戈登,我嘗試了你的建議,它幾乎完美地工作。問題是,當我真的需要總數下面的數字時,它給我一個數(總和),而不是記錄總和。有任何想法嗎?謝謝。 – user3560261

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子句列表必須是硬編碼的,你不能動態地使用子查詢生成一個列表。不過,這應該不會太難以開始填充。