2015-12-09 35 views
0

據說我有以下表格:計數的水桶 - PLSQL

ID Apple Orange Banana 
1 Y  Y  N 
2 N  Y  N 
3 Y  N  N 
4 Y  N  Y 

我應該怎麼寫在PLSQL查詢,這將給我下?

ID Apple Orange Banana 
Y 3  2  1 
N 1  2  3 

回答

3

下面是使用條件聚集的方法:

select x.id, 
     sum(case when apple = x.id then 1 else 0 end) as Apple, 
     sum(case when orange = x.id then 1 else 0 end) as Orange, 
     sum(case when banana = x.id then 1 else 0 end) as Banana 
from t cross join 
    (select 'Y' as id from dual union all 
     select 'N' from dual 
    ) x 
group by x.id; 
0
SELECT 'Y' id, 
    SUM(DECODE(apple,'Y',1)) apple_cnt, 
    SUM(DECODE(Orange,'Y',1)) Orange_cnt, 
    SUM(DECODE(Banana,'Y',1)) Banana_cnt 
FROM 
    (SELECT '1' ID, 'Y' Apple, 'Y' Orange, 'N' Banana FROM dual 
    UNION ALL 
    SELECT '2' , 'N', 'Y', 'N' FROM dual 
    UNION ALL 
    SELECT '3' , 'Y' , 'N' , 'N' FROM dual 
    UNION ALL 
    SELECT '4' , 'Y' , 'N' , 'Y' FROM dual 
) 
UNION ALL 
SELECT 'N' id, 
    SUM(DECODE(apple,'N',1)) apple_cnt, 
    SUM(DECODE(Orange,'N',1)) Orange_cnt, 
    SUM(DECODE(Banana,'N',1)) Banana_cnt 
FROM 
    (SELECT '1' ID, 'Y' Apple, 'Y' Orange, 'N' Banana FROM dual 
    UNION ALL 
    SELECT '2' , 'N', 'Y', 'N' FROM dual 
    UNION ALL 
    SELECT '3' , 'Y' , 'N' , 'N' FROM dual 
    UNION ALL 
    SELECT '4' , 'Y' , 'N' , 'Y' FROM dual 
) 
0

如果表中所顯示的結構是不是強制性的,我建議你結構是這樣的:

ID FRUIT FLAG 
1 Apple Y 
2 Apple Y 
3 Apple Y 
4 Apple N 
5 Orange N 
6 Orange N 
7 Orange N 
8 Orange Y 
9 Orange Y 
10 Banana Y 
11 Banana N 
12 Banana Y 
13 Banana Y 
14 Banana N 

對於此設計,您可以使用Pivot Query

SELECT * 
    FROM (SELECT Fruit, Flag FROM tab1) PIVOT (COUNT (Fruit) 
             FOR (fruit) 
             IN ('Apple' AS Apple, 
              'Orange' AS Orange, 
              'Banana' AS Banana)) 

結果:

FLAG APPLE ORANGE BANANA 
Y  3  2  3 
N  1  3  2 

另一種變體:

SELECT * 
    FROM (SELECT Fruit, Flag FROM tab1) PIVOT (COUNT (Flag) 
             FOR (Flag) 
             IN ('Y' AS Yes, 'N' AS No)) 

結果:

FRUIT YES NO 
Apple 3 1 
Orange 2 3 
Banana 3 2 
-1

下面這個查詢的工作!!! ..屢試不爽。

select id,sum(apple),sum(orange),sum(banana) 
from 
(select 'Y' ID, count(1)apple,0 orange, 0 banana from table_name where apple ='Y' 
UNION ALL 
select 'Y', 0 ,count(1),0 from table_name where orange ='Y' 
UNION ALL 
select 'Y',0, 0, count(1) from table_name where banana ='Y' 
UNION ALL 
select 'N', count(1),0,0 from table_name where apple ='N' 
UNION ALL 
select 'N', 0,count(1),0 from table_name where orange ='N' 
UNION ALL 
select 'N', 0,0,count(1) from table_name where banana ='N' 
) 
group by id;