SQL:在计算字段中查找最大行数

时间:2017-03-07 13:14:52

标签: mysql sql

我想在数据库中找到最大行数。在我的示例查询中,它返回如下内容:

executed query

但我只想要值为“110”的行。 我们无法使用having,因为最大值并非始终为“110”。它可以是“100”或“90”或......

这是我的SQL查询:

select q.id,q.question,
if(isnull(date),'1970-01-01 00:00:00',date)date, if(qimg='','',concat(''))qimg,
case concat(if(isnull(last),'n',last),
if(isnull(plast) or plast='','n',plast),
if(isnull(pplast)or pplast='','n',pplast))
when 'www' then '110' 
when 'wwr' then '110' 
when 'wwe' then '110' 
when 'wwn' then '110' 
when 'wrw' then '110' 
when 'wrr' then '110' 
when 'wre' then '110' 
when 'wrn' then '110' 
when 'wew' then '110' 
when 'wer' then '110' 
when 'wee' then '110' 
when 'wen' then '110' 
when 'wnn' then '110' 
when 'rww' then '110' 
when 'rwr' then '90' 
when 'rwe' then '90' 
when 'rwn' then '100' 
when 'rrw' then '75' 
when 'rrr' then '40' 
when 'rre' then '40' 
when 'rrn' then '50' 
when 'rew' then '60' 
when 'rer' then '25' 
when 'ree' then '25' 
when 'ren' then '35' 
when 'rnn' then '65' 
when 'eww' then '100' 
when 'ewr' then '65' 
when 'ewe' then '65' 
when 'ewn' then '75' 
when 'erw' then '50' 
when 'err' then '15' 
when 'ere' then '15' 
when 'ern' then '25' 
when 'eew' then '35' 
when 'eer' then '10' 
when 'eee' then '10' 
when 'een' then '10' 
when 'enn' then '40' 
when 'nnn' then '110' end point 
from question q left join answer a on q.id=qid and a.user_id=1 
where subject=2 and level<=3 order by date,id

感谢您的帮助?!

2 个答案:

答案 0 :(得分:0)

如果您想要的条件是“正好110”,那么您需要在case中复制那个巨大的where条款,例如

where case all-that-stuff end = 110

<强>但

如此庞大的列表表明您的模型可能存在问题;我会考虑将这些对保存在表中,然后您可以将其加入现有查询中。

CODE   VALUE
------------
'www'  '110' 
'wwr'  '110' 
'wwe'  '110' 
'wwn'  '110' 
...

select  q.id,q.question,
        if(isnull(date), '1970-01-01 00:00:00', date) date,
        if(qimg='', '', concat('')) qimg,
        p.value point 
from    question q
left join answer a
on      q.id=qid and a.user_id=1 
join    newtable p
on      concat(if(isnull(last),'n',last),
               if(isnull(plast) or plast='','n',plast),
               if(isnull(pplast)or pplast='','n',pplast)) = p.code
where   subject=2 and level<=3 and p.value = 110
order by date,id

修改

如果你总是希望过滤具有最大'point'值的行,那么我建议更多地将这些数据放在一个表中,或者如果计算是连续的,则在视图中。

你最终会得到像

这样的东西
select  q.id,q.question,
        if(isnull(date), '1970-01-01 00:00:00', date) date,
        if(qimg='', '', concat('')) qimg,
        p.value point 
from    question q
left join answer a
on      q.id=qid and a.user_id=1 
join    newtable p
on      concat(if(isnull(last),'n',last),
               if(isnull(plast) or plast='','n',plast),
               if(isnull(pplast)or pplast='','n',pplast)) = p.code
where   subject=2 and
        level<=3 and
        p.value = (select max(p.value) from newtable)
order by date,id

如果无法使用单独的表格,则必须将newtable的每一次出现都替换为您所写的那个巨大的case

答案 1 :(得分:0)

为什么不使用内嵌视图?

SELECT * FROM (your_query) temp 
WHERE Point = (SELECT MAX(Point) from (your_query) temp2)