2015-04-07 161 views
0

我正在使用SQL語言。我想結合查詢的結果。 這是我的代碼和預期的輸出。結合查詢的結果在sql

create table customer(name varchar,dpt varchar); 

insert into customer (name,dpt)VALUES ('albe','cse'); 
insert into customer (name,dpt)VALUES ('bine','cse'); 
insert into customer (name,dpt)VALUES ('alfred','ece'); 
insert into customer (name,dpt)VALUES ('booshan','ece'); 
insert into customer (name,dpt)VALUES ('antony','eee'); 
insert into customer (name,dpt)VALUES ('job','ece'); 

查詢1

select 
dpt, 
count(name) 
    from customer 
    where dpt='ece' or dpt='cse' 
    group by dpt; 

結果

| dpt | count | 
|-----|-------| 
| cse | 2 | 
| ece | 3 | 

我所需要的結果爲:

| cse/ece | 5 | 

怎麼可能? sqlfiddle是在這裏:

http://sqlfiddle.com/#!12/a1c88/13

回答

5

好像你正在使用PostgreSQL(這可以從sqlfiddle鏈接推斷)。

如果是這種情況,那麼您可以在外部查詢適用於你的查詢array_aggsum

SELECT array_agg(dpt), sum(cnt) 
    FROM (
     SELECT dpt, count(name) as cnt 
     FROM customer 
     WHERE dpt='ece' OR dpt='cse' 
     GROUP BY dpt) t; 

SQL Fiddle Demo

+0

謝謝.....它運作良好。 –

1

您也可以使用GROUP_CONCAT

SELECT GROUP_CONCAT(dpt), SUM(cnt) 
FROM(select 
    dpt, 
    count(name) cnt 
    from customer 
    where dpt='ece' or dpt='cse' 
    group by dpt) t; 

SQL Fiddle