2014-09-30 71 views
0

下表試想:有GROUP BY多個值給我的所有可能的組合

type cond 
A good 
A good 
A bad 
B good 
B bad 
C good 
C bad 
D good 
D bad 
E worse 

如果我算和組雙方typecond我會得到這樣的:

count type cond 
2  A good 
1  A bad 
1  B good 
1  B bad 
1  C good 
1  C bad 
1  D good 
1  D bad 
1  E worse 

但對於更好地將數據總結成表格我寧願喜歡這樣的結果:

count type cond 
2  A good 
1  A bad 
0  A worse 
1  B good 
1  B bad 
0  B worse 
1  C good 
1  C bad 
0  C worse 
1  D good 
1  D bad 
0  D worse 
0  E good 
0  E bad 
1  E worse 

我已經設法交叉加入所有現有的type s與所有現有的cond s,但我不能再計算了。 我也嘗試將結果與所有現有的type s或cond s結合,但這也不起作用。

SUM-CASE-WHEN策略在這裏不起作用,因爲我想讓它具有動態性,即我不知道會有多少個typecond

是否有一個簡單的(甚至是複雜的)解決方案來生成分組數據的線性矩陣? (獎勵:...甚至調換它,即二維矩陣,有一個組的表頭?)

+0

有你值父表中的 「好」, 「壞」, 「雪上加霜」? – 2014-09-30 07:37:07

+0

@JoeTaras:我沒有一個包含所有可能條件的表,但它可以通過'SELECT cond FROM table GROUP BY cond'動態地合成(並嵌套,如果需要的話)' – dulange 2014-09-30 07:39:47

+0

Ook,關於規範化,最好是你有一張表那些價值。 – 2014-09-30 08:00:33

回答

0

試試這個:

SELECT 
    COUNT(c.type) as `count`, a.type, b.cond 
FROM (
    SELECT DISTINCT type 
    FROM table_name 
) a 
    CROSS JOIN (
    SELECT DISTINCT cond 
    FROM table_name 
) b 
    LEFT JOIN 
    table_name c ON c.type = a.type AND c.cond = b.cond 
GROUP BY a.type, b.cond 
ORDER BY a.type, b.cond 

測試:SQL Fiddle

編輯:

要在一個組中以二維矩陣的形式顯示結果作爲表頭,必須在運行查詢之前知道組名稱。查詢可以是:

SELECT 
    a.type, 
    COUNT(CASE WHEN b.cond = 'good' THEN c.type ELSE NULL END) as good, 
    COUNT(CASE WHEN b.cond = 'bad' THEN c.type ELSE NULL END) as bad, 
    COUNT(CASE WHEN b.cond = 'worse' THEN c.type ELSE NULL END) as worse 
FROM (
    SELECT DISTINCT type 
    FROM table_name 
) a 
    CROSS JOIN (
    SELECT DISTINCT cond 
    FROM table_name 
) b 
    LEFT JOIN 
    table_name c ON c.type = a.type AND c.cond = b.cond 
GROUP BY a.type 
ORDER BY a.type 

測試:SQL Fiddle

0

爲了更好的數據結構必須有一個表cond anagraph但是......

你可以用兩個子查詢,一個建立自己的笛卡爾乘積對於所有類型和所有類型的情況,因此,您在SELECT字段中有一個子查詢,您可以計算這些情侶的元素。

試試這個:

CREATE TABLE app(type char, cond varchar(10)); 

INSERT INTO app values 
('A', 'good'), 
('A', 'good'), 
('A', 'bad'), 
('B', 'good'), 
('B', 'bad'), 
('C', 'good'), 
('C', 'bad'), 
('D', 'good'), 
('D', 'bad'), 
('E', 'worse') 

select t1.cond, t2.type, (select count(*) from app a3 where a3.cond = t1.cond 
and (a3.type = t2.type)) as total 
from 
    (select distinct cond 
    from app a1) as t1 
cross join 
    (select distinct type 
    from app a2) as t2 
order by t2.type, t1.cond 

Show SqlFiddle

0
select 
    A.type, 
    A.cond, 
    case 
     when B.cnt is null then 0 
     else B.cnt 
    end 
from 
    (select 
     type, cond 
    from 
     (SELECT distinct 
     cond 
    from 
     package) 
    cross join (select distinct 
     type 
    from 
     package)) A 
     left join 
    (select 
     type, cond, count(*) as cnt 
    from 
     package 
    group by type , cond) B ON A.cond = B.cond and A.type = B.type 
order by type 
+0

有人可以縮進它不能 – 2014-09-30 09:12:17