如何在MySQL查询结果中找到两行的差异

时间:2014-11-30 00:20:12

标签: mysql sql subquery

我有以下MySQL查询:

SET @rowno= 0;
SELECT @rowno:=@rowno+1 AS `row`,`year`,`year_average` FROM(
/*get the average from the start of the 10 year period and the current period*/  

SELECT year,AVG(value) AS year_average FROM
/* get all records that have technical and trade school industry code */
(SELECT * FROM `allcesseries`
   WHERE series_id LIKE concat('%',(SELECT industry_code FROM `ceindustry` WHERE industry_name LIKE      '%Technical and trade schools%'),'%')) AS trade_schools
WHERE trade_schools.year = (2014-10) OR trade_schools.year = 2014
GROUP BY year) AS t

返回值

row | year | year_average
 1    2004   76.24
 2    2014   99.9

我似乎无法弄清楚如何区分第1行的平均值和第2行的平均值。

1 个答案:

答案 0 :(得分:1)

使用MySQL

SELECT (
  (SELECT AVG(value)
  FROM allcesseries
  WHERE series_id LIKE concat('%',(SELECT industry_code FROM `ceindustry` WHERE industry_name LIKE '%Technical and trade schools%'),'%')
    AND year = 2014)
  -
  (SELECT AVG(value)
  FROM allcesseries
  WHERE series_id LIKE concat('%',(SELECT industry_code FROM `ceindustry` WHERE industry_name LIKE '%Technical and trade schools%'),'%')
    AND year = 2004)
) AS difference
;

应该有效。见proof of concept。如果不适合您的情况(或需要调整),请提供SQL Fiddle表结构和样本数据。