2011-09-23 189 views
1

我正在使用MySQL 5.5。我有一個查詢返回這樣如何從MySql中的選擇查詢中選擇數據?

quantity| maxPrice| minPrice |avgPrice| counts 
"10" "23.50" "23.50" "23.500000" "1" 
"15" "15.75" "15.75" "15.750000" "1" 
"23" "100.71" "100.71" "100.710000" "1" 
"25" "210.00" "200.00" "205.000000" "2" 
現在從這個數據我想提取所有計數的最大數量的元組與和

結果......,這樣的結果是這樣的

quantity| maxPrice| minPrice |avgPrice| counts 
"25" "210.00" "200.00" "205.000000" 5 

我該如何編寫查詢?

回答

1

使用ORDER BY quantity DESCLIMIT 1提取元組。用另一個選擇環繞您的查詢,並使用SUM(counts) AS counts

SELECT 
x.quantity, x.maxPrice, x.minPrice, 
x.avgPrice, SUM(x.counts) AS counts 
FROM 
(
SELECT * 
FROM mytable 
ORDER BY quantity DESC 
) AS x 
LIMIT 1; 

替換SELECT * FROM mytable與你的真實的查詢。

+0

謝謝,這真的很有幫助,聰明:) – Shreyash

+0

歡迎來到stackoverflow :)。如果您覺得這是正確的答案,請不要忘記接受它。 –

1
SELECT 
    max(s.quantity) as quantity 
    , max(s.maxPrice) as maxPrice 
    , max(s.minPrice) as minPrice 
    , max(s.AvgPrice) as avgPrice 
    , max(s.totalcounts) as totalcounts 
    FROM (
     SELECT t1.quantity,t1.maxPrice,t1.minPrice,t1.avgPrice, 0 as totalcounts 
     FROM table1 t1 
     ORDER BY quantity DESC 
     LIMIT 1 
    UNION 
     SELECT 0,0,0,0,sum(t2.counts) as totalcounts 
     FROM table1 t2 
    ) s