Mysql Group by With Condition

时间:2014-05-07 06:34:25

标签: mysql

以下数据显示了具有学生选修/非选修科目的时间表。我的要求是当elec和nonelec类型具有相同的周期时选择那些行,因此在这种情况下选择elec类型。

当两者都具有相同的时候,应该优先考虑选择日期的选项(类型elec)期。当类型elec没有像时期5那样的时期时,则选择非选择性的。

enter image description here

我的查询

SELECT s.sch_id, s.sch_subtype, sd.sdetail_id, sd.sdetail_period
FROM schedule s
INNER JOIN schedule_detail sd ON s.sch_id = sd.sdetail_schedule
WHERE  '2014-04-30'
BETWEEN sch_datefrom
AND sch_dateto
AND 
(
  (
    sch_section =1
    AND sch_subtype =  'nonelec'
  )
  OR 
  (
    sch_subtype =  'elec'
    AND 272 
    IN 
    (    
      SELECT edetail_stuid
      FROM elective_detail
      WHERE edetail_elective = sch_section
    )
  )
)
AND sch_course =3
AND sch_batch =2
AND sch_termid =2
AND sdetail_day =  'wed'
AND sdetail_period >0
AND CASE WHEN sch_subtype =  'nonelec'
THEN 1 =1
WHEN sch_subtype =  'elec'
THEN sdetail_subject >0
AND sdetail_faculty >0
AND sdetail_room >0
END GROUP BY CASE WHEN sch_subtype =  'elec'
THEN sdetail_period
ELSE 1 
END ORDER BY sdetail_period

以上查询的输出

enter image description here

所需输出

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以尝试这种方式:

SELECT sch_id,sch_subtype,sdetail_id,sdetail_period 
FROM table 
WHERE condition 
group by sch_subtype

如果您可以发布您尝试过的查询,那会更好。

答案 1 :(得分:0)

这里的问题真的不明白:

SELECT * FROM schedule s
JOIN schedule_detail sd ON s.sch_id = sd.sdetail_schedule
LEFT JOIN elective_detail ed ON sd.sch_section = ed.edetail_elective
WHERE
(
  sd.sch_section =1
  AND s.sch_subtype =  'nonelec'
)
OR
(
  ed.edetail_stuid = 227
  AND sch_subtype =  'elec'
)
GROUP BY sd.sdetail_period

SQL小提琴:http://sqlfiddle.com/#!2/69d4e/1