MYSQL - 仅将 where 子句应用于某些字段

标签 mysql where-clause

我在 MYSQL 中有这个表:

Year    Type    Value  ID

0       0       5      1
2010    1       6      1
2011    1       4      1
2012    1       5      1
2013    1       7      1
2014    1       8      1
2015    1       5      1
0       0       6      2
2009    1       7      2
2010    1       4      2
2011    1       2      2
2012    1       8      2
2013    1       8      2
2014    1       5      2

我想为每个人(ID 1 和 2)选择最小和最大年份,但我也想为每个人选择与类型 0 关联的值。理想情况下,查询结果应该是这样的:

ID   MinYear    MaxYear    Type0Value
1    2010       2015       5
2    2009       2014       6

我认为查询应该看起来像这样......

select ID, 
(min(year) where type = 1) as MinYear, 
(max(year) where type = 1) as MaxYear,
(value where type = 0) as Type0Value
from table
group by ID

但这显然不是正确的 SQL 语法。我该怎么做?

最佳答案

奇怪的表结构,但是:

select
    _type0.id,
    _type0.value,
    _type1._min,
    _type1._max
from
    tbl as _type0
    inner join (
        select
            id,
            min(year) as _min,
            max(year) as _max
        from
            tbl
        where
            1 = type
        group by
            id
    ) as _type1 on
        _type0.id = _type1.id
where
    0 = _type0.type;

关于MYSQL - 仅将 where 子句应用于某些字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31505649/

相关文章:

sql - 如何编写仅在 where 子句中使用的函数,该函数在没有比较运算符的情况下计算为 true?

mysql - 使用 include 在何处进行 Sequelize

PHP/MYSQL 返回不正确的结果 - MYSQL WHERE 子句

mysql - Ruby on Rails 无法从运行器脚本连接到数据库

php - php 中 mysql BLOB 操作

mysql - 如何比较mysql中的逗号分隔值?

mysql - 使用数组在两个日期之间插入

arrays - Loopback where 数组类型字段上的过滤器

php - sql 查询未从 php 中的对象方法内触发

php - 选择 1 虽然用户很少.. mysql