mysql - 复杂的? MySQL查询

标签 mysql

我有一个包含列、id、日期、estValue 和 Gradeid 的表。每个成绩 ID 大约有 12 条记录,大约有 10 个不同的成绩,总共大约 120 条记录[给出或接受]我需要从数据库中创建一个选择,为我提供一个如下所示的结果集:


date    |gradeid1 |gradeid2 |gradeid3 3|etc...
01/01/01|estValue1|estValue2||estValue3|etc....
01/01/02|estValue1|estValue2||estValue3|etc....

我有一个可以选择一条记录的查询,但我需要将它们全部按日期排序:


select eh.id, eh.date as wdate,
    (select estValue from nas_estimatehistory where `date` like '2011-03-%' and gradeid = '1') as '1',
    (select estValue from nas_estimatehistory where `date` like '2011-03-%' and gradeid = '2') as '2',
    (select estValue from nas_estimatehistory where `date` like '2011-03-%' and gradeid = '3') as '3',
    (select estValue from nas_estimatehistory where `date` like '2011-03-%' and gradeid = '4') as '4',
    (select estValue from nas_estimatehistory where `date` like '2011-03-%' and gradeid = '5') as '5',
    (select estValue from nas_estimatehistory where `date` like '2011-03-%' and gradeid = '6') as '6',
    (select estValue from nas_estimatehistory where `date` like '2011-03-%' and gradeid = '7') as '7',
    (select estValue from nas_estimatehistory where `date` like '2011-03-%' and gradeid = '8') as '8',
    (select estValue from nas_estimatehistory where `date` like '2011-03-%' and gradeid = '9') as '9',
    (select estValue from nas_estimatehistory where `date` like '2011-03-%' and gradeid = '10') as '10'
from nas_estimatehistory eh  
group by wdate 
order by `wdate` asc
limit 1;

它返回几乎我需要的内容,但只有 1 行,如果我删除限制,那么我每个月都会得到一行 [12 行],但所有列值都是相同的 [它们应该都不同],即每行和列中的 estValue 应该是唯一的值...

我不确定最好的方法是什么。

-谢谢 -肖恩

最佳答案

Cross-tabulation关键是:使用aggregate functionIF 函数。

SELECT eh.date AS wdate,
    GROUP_CONCAT(IF(gradeid=1,estValue,NULL)) as `1`,
    GROUP_CONCAT(IF(gradeid=2,estValue,NULL)) as `2`,
    GROUP_CONCAT(IF(gradeid=3,estValue,NULL)) as `3`,
    GROUP_CONCAT(IF(gradeid=4,estValue,NULL)) as `4`,
    GROUP_CONCAT(IF(gradeid=5,estValue,NULL)) as `5`,
    GROUP_CONCAT(IF(gradeid=6,estValue,NULL)) as `6`,
    GROUP_CONCAT(IF(gradeid=7,estValue,NULL)) as `7`,
    GROUP_CONCAT(IF(gradeid=8,estValue,NULL)) as `8`,
    GROUP_CONCAT(IF(gradeid=9,estValue,NULL)) as `9`,
    GROUP_CONCAT(IF(gradeid=10,estValue,NULL)) as `10`
FROM nas_estimatehistory eh  
GROUP BY wdate 
ORDER BY `wdate` ASC;

MAXMIN 也可能是合适的聚合函数。

关于mysql - 复杂的? MySQL查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5443849/

相关文章:

mysql - 使用查询中的博客 ID 获取博客类别和关键字

php - PHP 脚本中未输出 XML

php - 无法动态创建表名中带有空格的表

Bash 中的 MySQL 错误

mysql - SQL - 检索过去 7 天的最后一天记录

MySql:如果在函数内部或外部调用,相同的 select count(*) 查询将返回不同的结果

mysql - 连接同一个表并在mysql查询中获取子文件夹

php - 如何让我的点击计数器每天、每周和每月进行计数?

php - MYSQL WHERE 子句是错误的值

mysql - 在 where 子句中使用别名 - SQL