从结果中获取最高价值

时间:2014-03-05 05:44:36

标签: mysql sql

我有一张桌子

t1
--------------
id
date
val_1
val_2

我需要获得10个最新结果,并将它们从早期到最晚的日期排序,所以我这样做

SELECT * FROM (
        SELECT *
        FROM myTable
        WHERE project = $project_id
        ORDER BY date DESC
        LIMIT 10) AS results ORDER BY id ASC

现在,我需要获得val_1的最高值。我正在尝试构建一个条形图,并希望获得最高值,因为我需要将其除以最大高度,并将该结果用作乘数,以便将val_1和val_2叠加在一起,而不会超出图的高度。

6 个答案:

答案 0 :(得分:0)

尝试

SELECT val_1 as max_val FROM myTable ORDER by val_1 DESC LIMIT 1

您也可以尝试使用MAX

SELECT MAX(val_1) as max_val FROM myTable

答案 1 :(得分:0)

你可以试试这个:

SELECT *, MAX(val_1) FROM (
    SELECT *
    FROM myTable
    WHERE project = $project_id
    ORDER BY date DESC
    LIMIT 10) AS results ORDER by id ASC

答案 2 :(得分:0)

请参阅3.6.1 The Maximum Value for a Column

  

“最高的项目编号是多少?”

SELECT MAX(article) AS article FROM shop;

您也可以在查询结果中使用MAX()

SELECT MAX(val_1) FROM (SELECT …) t;

答案 3 :(得分:0)

做类似的事情;

SELECT MAX(val_1) FROM(SELECT *
        FROM myTable
        WHERE project = $project_id
        ORDER BY date DESC
        LIMIT 10) AS results ORDER by id ASC

答案 4 :(得分:0)

所以你想要这样的东西?

  SELECT *, 
         t2.biggest_value,
         ((t1.val_1/t2.biggest_value)*100) AS `%`
    FROM myTable t1
    JOIN (SELECT MAX(val_1) AS biggest_value,
                 project
            FROM myTable
         ) AS t2
      ON t2.project = t1.project
   WHERE t1.project = $project_id
ORDER BY date DESC, id ASC 
   LIMIT 10

JOIN获得val_1的最高值,外部查询收集所有数据,并根据最大值计算每个val_1的百分比。

Live DEMO

答案 5 :(得分:0)

此查询会为您提供其他列的最大值: -

SELECT id,(select MAX(`price`) FROM `products` ) as FINAL from products

注意: - 此查询汇总产品表中的ID和最高价格.i.e它将最高价格与每个记录集相关联。