mysql-如何将简单选择转换为更复杂的查询

时间:2013-12-19 16:57:10

标签: mysql sql

我有这个基本的sql查询,它获得“1级”的平均分数和总分数,并输出到csv文件

SELECT judge,AVG(score), count(judge) 
FROM results 
WHERE judge NOT LIKE '% AND %' 
  AND score >30 
  AND (class like '%1st%' OR class LIKE '%first%' OR class LIKE '%1 st%')
GROUP BY judge 
INTO OUTFILE 'c:/py/2013/all/judges-by-level.csv'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n';

我想扩展此查询以从多个“级别”获得平均分数(从类列的字符串值派生)我当前的级别1 WHERE如下所示:
class LIKE '%1st%' OR class LIKE '%first%' or class LIKE '%1 st%'

我想使用类似的LIKE来更改此查询以获得级别2,级别3等 (class LIKE '%2nd%' OR class LIKE '%second%' OR class LIKE '%2 nd%'

原始数据如下:

judge   , score  ,class
John Doe, 55.123 ,First Level Championship
Jane Doe, 65.123 ,1st Amateur Division
John Doe, 75.123 ,Second Level Championship

我要输出的输出是一个格式如下的csv文件:

judge, level1_avg, level1_count, level2_avg, level2_count
John Doe,55.567,123,51.123,88
Jane Doe,58.123,66,53.123,247

我将使用哪种SQL语法来获得所需的输出?

2 个答案:

答案 0 :(得分:1)

您想基于first/1st/1 stsecond/2nd/2 nd进行交叉制表吗?

作为一个侧面点,LIKE ... OR LIKE ... OR LIKE可以用正则表达式替换以缩短事物。

假设我正确地解答了你的问题,这应该接近你所需要的:

SELECT
  judge,
  AVG(case when class rlike '1st|first|1 st' THEN score END) level1_avg,
  COUNT(case when class rlike '1st|first|1 st' THEN judge END) level1_count,
  AVG(case when class rlike '2nd|second|2 nd' THEN score END) level2_avg,
  COUNT(case when class rlike '2nd|second|2 nd' THEN judge END) level2_count
FROM results
where judge not like '% and %' AND score > 30
group by judge
INTO OUTFILE 'c:/py/2013/all/judges-by-level.csv'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n';

拆分level1_avg结果列:

  • 如果class包含1stfirst1 st,则CASE会返回score,因此它会包含在平均值中。
  • 如果class不包含1stfirst1 st,则CASE会返回null,因此不< / em>包含在平均值中。

其他聚合列使用类似的逻辑。

答案 1 :(得分:0)

试试工会?虽然在这么多级别之后这不会有效。 (注意INTO OUTFILEORDER BY在最后的联合条款中)

SELECT judge, AVG(score) as 'level1_avg', count(judge) as 'level1_count', '' as 'level2_avg', '' as 'level2_count', '' as 'level3_avg', '' as 'level3_count'  
FROM results 
WHERE judge NOT LIKE '% AND %' 
   AND score >30 
   AND (class like '%1st%' OR class LIKE '%first%' OR class LIKE '%1 st%')
GROUP BY judge

UNION ALL

SELECT judge, '' as 'level1_avg', '' as 'level1_count', AVG(score) as 'level2_avg', count(judge) as 'level2_count', '' as 'level3_avg', '' as 'level3_count'
FROM results 
WHERE judge NOT LIKE '% AND %' 
   AND score >30 
   AND (class like '%2nd%' OR class LIKE '%second%' OR class LIKE '%2 nd%')
GROUP BY judge    

UNION ALL

SELECT judge, '' as 'level1_avg', '' as 'level1_count', '' as 'level2_avg', '' as 'level2_count', AVG(score) as 'level3_avg', count(judge) as 'level3_count' 
   INTO OUTFILE 'c:/py/2013/all/judges-by-level.csv'
   FIELDS TERMINATED BY ','
   LINES TERMINATED BY '\r\n';
FROM results 
WHERE judge NOT LIKE '% AND %' 
   AND score >30 
   AND (class like '%3rd%' OR class LIKE '%third%' OR class LIKE '%3 rd%')
GROUP BY judge   
ORDER BY judge

编辑:在联盟的适当列中添加了空白