MySQL:案例查询中的案例查询?

时间:2016-08-02 04:13:18

标签: mysql sql mysql-workbench

我有一个查询可以获得单位数,如果已经完成则会标记。

SELECT distinct location, 
case when  id is NULL then 'Not Started'
 when '1'  then 'Completed' 
 else 'In Progress' end   as Remarks,
count(name) as CountName
FROM table
group by location,
case when  id is NULL then 'Not Started'
 when '1'  then 'Completed' 
 else 'In Progress' end;

结果:

enter image description here

但我想将其概括如下图:

enter image description here

条件是当位置中有两(2)个备注时,它应被标记为"正在进行中"并将CountName相加。但是,当只有一个位置备注时,将备注作为其标记。

3 个答案:

答案 0 :(得分:3)

对此不确定(样本数据会有所帮助),但请尝试以下方法:

SELECT Location, 
    case when count(id) > 1 then 'In Progress'
         when max(id) is null then 'Not Started'
         when max(id) = 1 then 'Completed'
         else 'In Progress' end As Remarks,
    count(name) as CountName
FROM table
GROUP BY location

答案 1 :(得分:1)

就像你说的,案件中的一个案例:

select location,
       case when count(distinct case when id is null then 'Not Started'
                                     when id = '1' then 'Completed'
                                     else 'In Progress' end) > 1
            then 'In Progress'
            else max(case when id is null then 'Not Started'
                          when id = '1' then 'Completed'
                          else 'In Progress' end)
        end as remarks,
        count(*) as CountName
  from tbl
 group by location

SQLFiddle Demo

答案 2 :(得分:0)

尝试此查询: -

SELECT location, 
       if(count(1) > 1, 'In Progress', Remarks) Remarks, 
       sum(countName) countName 
   FROM location 
   group by location