如何从MySql中的选择查询中选择数据?

时间:2011-09-23 13:52:02

标签: mysql

我正在使用MySQL 5.5。我有一个返回结果的查询

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

如何为此编写查询?

2 个答案:

答案 0 :(得分: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替换为您的真实查询。

答案 1 :(得分: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