2015-11-03 60 views
0

我有這個疑問:SQL一行輸出

SELECT Count(*) AS GesamtanzahlMitarbeiter, 
(SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%80') AS "1980", 
(SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%81') AS "1981", 
(SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%82') AS "1982", 
(SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%83') AS "1983" 
FROM EMP 
GROUP BY DEPTNO; 

而且我得到這樣的輸出:

GESAMTANZAHLMITARBEITER  1980  1981  1982  1983 
----------------------- ---------- ---------- ---------- ---------- 
         6   1   10   2   1 
         5   1   10   2   1 
         3   1   10   2   1 

現在問題的關鍵是,我不要想組DEPTNO。我想組所有這些,指望所有的「GESAMTANZAHLMITARBEITER」是這樣的:

GESAMTANZAHLMITARBEITER  1980  1981  1982  1983 
----------------------- ---------- ---------- ---------- ---------- 
        14   1   10   2   1 

但我不能GROUP BY *或東西.. 一種解決方法是給他們都具有相同的值的新屬性,按該屬性分組,但那只是不正確。

我不知道該怎麼做......

+0

只是刪除分組.. –

+0

然後我收到錯誤信息,它似乎需要分組,如果你使用count() – jochot

回答

4

使用條件的聚集,在SUM

SELECT 
    COUNT(*) as GesamtanzahlMitarbeiter, 
    SUM(CASE WHEN HIREDATE LIKE '%80'THEN 1 ELSE 0) as "1980", 
    SUM(CASE WHEN HIREDATE LIKE '%81'THEN 1 ELSE 0) as "1981", 
    SUM(CASE WHEN HIREDATE LIKE '%82'THEN 1 ELSE 0) as "1982", 
    SUM(CASE WHEN HIREDATE LIKE '%83'THEN 1 ELSE 0) as "1983" 
FROM EMP 

注意添加case如果添加GROUP BY到這個查詢,你會得到COUNT(*)每個emp在您先前的查詢中,您將獲得每行中所有表的COUNT(*)

+0

謝謝!我知道它不會用Group By這樣的方式解決.. :) – jochot

1

您可以使用count沒有group by這樣的:

SELECT 
(SELECT Count(*) FROM EMP) AS GesamtanzahlMitarbeiter, 
(SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%80') AS "1980", 
(SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%81') AS "1981", 
(SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%82') AS "1982", 
(SELECT Count(*) FROM EMP WHERE HIREDATE LIKE '%83') AS "1983" 
FROM DUAL; 
0

這個怎麼樣(假設一個比較新的Oracle版本):

with pivot_data as 
    (select to_number(to_char(hiredate,'YYYY')) as year 
     from emp) 
    , pivotted as 
    (select * 
     from pivot_data pd 
     pivot (count(year) for year in (1980, 1981, 1982, 1983))) 
    , totals as 
    (select count(*) as GesamtanzahlMitarbeiter from pivot_data) 
select t.GesamtanzahlMitarbeiter 
    , p.* 
from pivotted p cross join totals t;