2016-10-25 72 views
0

我有一個表1訪問SQL GROUPBY

pbsc qty wt 

pbsc1 1 0 
pbsc2 2 10 
pbsc3 1 0 
pbsc2 2 9  
pbsc1 0 8 
pbsc4 9 9 

我試圖從表1得到2個結果集(2個查詢表)

總結一下數量和重量外周血幹細胞是否也有類似的數據,該查詢我用

SELECT Table1.pbsc, sum(Table1.qty) As quantity , sum(Table1.wt) As 
> Weight 
>  FROM Table1 group by Table1.pbsc; 

這給了我

pbsc quantity Weight 
pbsc1 1    8 
pbsc2 4   19 
pbsc3 1    0 
pbsc4 9    9 

,但我試圖讓只有pbsc1,pbsc2因爲因爲它們比發生在表1一次一個結果集,作爲RESULT1

pbsc qty wt 
    pbsc1  1  8 
    pbsc2  4  19 

RESULT2應該像(因爲pbsc3,僅出現一次pbsc4)

pbsc qty wt 
    pbsc3 1 0 
    pbsc4 9 9 

回答

1

- 更多比一個p BSC。

SELECT Table1.pbsc, 
     sum(Table1.qty) As quantity , 
     sum(Table1.wt) As Weight 
    FROM Table1 
group by Table1.pbsc 
having count(*) > 1; 

- 僅限pbsc的一條記錄。

SELECT Table1.pbsc, 
     sum(Table1.qty) As quantity , 
     sum(Table1.wt) As Weight 
    FROM Table1 
group by Table1.pbsc 
having count(*) = 1; 
0
SELECT Table1.pbsc, 
     SUM(Table1.qty) AS Quantity, 
     SUM(Table1.wt) AS Weight 
FROM Table1 
WHERE Table1.pbsc IN (psc1, pbsc2) 
GROUP BY Table1.pbsc 

SELECT Table1.pbsc, 
     SUM(Table1.qty) AS quantity, 
     SUM(Table1.wt) AS Weight 
FROM Table1 
WHERE Table1.pbsc IN (psc3, pbsc4) 
GROUP BY Table1.pbsc