同一查询中的多个max()

时间:2012-10-15 12:56:27

标签: mysql sql

美好的一天,

我有: -

 SELECT MAX(register_number) AS "Next-6-months-register-number" 
    FROM gypsum WHERE test_frequency ='6'

我想在同一个查询中返回test_frequency ='3''12'的值。这可能吗? 谢谢GWS。

6 个答案:

答案 0 :(得分:5)

是的,这是可能的。使用GROUP BY获取每个组的最大值:

SELECT test_frequency, MAX(register_number) AS "Max-register-number"
FROM gypsum
WHERE test_frequency IN ('3', '6', '12')
GROUP BY test_frequency

答案 1 :(得分:0)

SELECT 
  MAX(CASE WHEN test_frequency = '3' THEN register_number END) 
      AS "Next-3-months-register-number",
  MAX(CASE WHEN test_frequency = '12' THEN register_number END) 
      AS "Next-12-months-register-number",
  MAX(CASE WHEN test_frequency = '6' THEN register_number END) 
      AS "Next-6-months-register-number",
  MAX(register_number) AS "Next-6-months-register-number" 
FROM gypsum 

答案 2 :(得分:0)

试试这个

SELECT MAX(CASE 
                WHEN test_frequency ='6' THEN register_number 
           ELSE NULL END) AS "Next-6-months-register-number" ,
      MAX(CASE 
                WHEN test_frequency ='3' THEN register_number 
           ELSE NULL END) AS "Next-3-months-register-number" ,
     MAX(CASE 
                WHEN test_frequency ='12' THEN register_number 
           ELSE NULL END) AS "Next-12-months-register-number" 
FROM gypsum

答案 3 :(得分:0)

获取所有test_frequency的最大值

SELECT test_frequency ,MAX(register_number) AS "Next-6-months-register-number" 
FROM gypsum 
group by test_frequency 

OR

SELECT MAX(register_number) AS "Next-6-months-register-number" 
FROM gypsum WHERE test_frequency in('6','3','12')
group by test_frequency 

答案 4 :(得分:0)

您应该只需使用 OR 关键字添加额外参数。

SELECT MAX(register_number) AS "Next-6-months-register-number" FROM gypsum 
WHERE test_frequency ='6'
or 
test_frequency ='3'
or
test_frequency ='12'

答案 5 :(得分:0)

在这里,您可以添加测试频率..('3','12)..或从查询中选择:

SELECT test_frequency, MAX(register_number) AS "Max-register-number"
FROM gypsum
WHERE test_frequency IN ('3','12')
GROUP BY test_frequency

SELECT test_frequency, MAX(register_number) AS "Max-register-number"
FROM gypsum
WHERE test_frequency IN (select frequency_colname from tablename where colname=value)
GROUP BY test_frequency