2017-10-05 53 views
0

,我有以下數據:計數由

data

而且我想知道每個值在每列多久存在。所以我的參訪輸出應該是這樣的:

output

我會非常感激,如果有人能幫助我。謝謝!

+1

您使用的是什麼RDBMS?請標記。另外,你到目前爲止嘗試過什麼?顯示你的努力.. –

+0

請粘貼文本,而不是圖像。你有什麼嘗試,你卡在哪裏? –

+0

我還沒有嘗試過很多,因爲我沒有真正的線索 – Nico

回答

0

這是一個奇怪的表結構和/或任務。你可能想考慮一下你的數據庫設計。反正...

select 
    num, 
    coalesce(agga.cnt, 0) as a, 
    coalesce(aggb.cnt, 0) as b, 
    coalesce(aggc.cnt, 0) as c, 
    coalesce(aggd.cnt, 0) as d 
from   (select a as num, count(*) as cnt from mytable group by a) agga 
full outer join (select b as num, count(*) as cnt from mytable group by b) aggb using(num) 
full outer join (select c as num, count(*) as cnt from mytable group by c) aggc using(num) 
full outer join (select d as num, count(*) as cnt from mytable group by d) aggd using(num) 
order by num; 
1

使用UNPIVOT然後PIVOT

SQL Fiddle

的Oracle 11g R2架構設置

CREATE TABLE table_name (a, b, c, d) AS 
SELECT 1, 2, 1, 2 FROM DUAL UNION ALL 
SELECT 1, 2, 2, 2 FROM DUAL UNION ALL 
SELECT 2, 1, 3, 3 FROM DUAL UNION ALL 
SELECT 3, 3, 2, 4 FROM DUAL UNION ALL 
SELECT 4, 4, 2, 5 FROM DUAL UNION ALL 
SELECT 5, 5, 5, 5 FROM DUAL; 

查詢1

SELECT * 
FROM table_name 
UNPIVOT(value FOR name IN (A, B, C, D)) 
PIVOT (COUNT(1) FOR name IN ('A' AS A, 'B' AS B, 'C' AS C, 'D' AS D)) 

Results

| VALUE | A | B | C | D | 
|-------|---|---|---|---| 
|  1 | 2 | 1 | 1 | 0 | 
|  2 | 1 | 2 | 3 | 2 | 
|  4 | 1 | 1 | 0 | 1 | 
|  5 | 1 | 1 | 1 | 2 | 
|  3 | 1 | 1 | 1 | 1 | 
1
with 
    inputs (a, b, c, d) as (
     select 1, 2, 1, 2 from dual union all 
     select 1, 2, 2, 2 from dual union all 
     select 2, 1, 3, 3 from dual union all 
     select 3, 3, 2, 4 from dual union all 
     select 4, 4, 2, 5 from dual union all 
     select 5, 5, 5, 5 from dual 
    ) 
-- End of simulated inputs (for testing only, not part of the solution). 
-- SQL query begins BELOW THIS LINE. Use your actual table and column names. 
select grade, 
     count(case when a = grade then 0 end) as a, 
     count(case when b = grade then 0 end) as b, 
     count(case when c = grade then 0 end) as c, 
     count(case when d = grade then 0 end) as d 
from inputs cross join (select level as grade from dual connect by level <= 5) 
group by grade 
order by grade 
; 

    GRADE   A   B   C   D 
---------- ---------- ---------- ---------- ---------- 
     1   2   1   1   0 
     2   1   2   3   2 
     3   1   1   1   1 
     4   1   1   0   1 
     5   1   1   1   2 

注意:這是基本相同MT0的解決方案,但無論是unpivoting和旋轉都完成了「老辦法」(因爲他們以前做過PIVOT和UNPIVOT操作員是在Oracle 11.1中引入的)。

+1

與'UNPIVOT' /'PIVOT'相比,最大的區別就是你需要用這個方法知道表中值的個數/範圍,這樣'LEVEL <= 5'子句產生足夠的行。 – MT0

+0

@ MT0 - 正確 - 事實上,我的「NOTE」並不完全正確,因爲我並不真正無意義,我仍然保留原來的行。 – mathguy