[英]MYSQL - apply a where clause to only some fields
我在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;
您应该使用内部联接。 一半将处理最小值和最大值,另一半将处理type0值:
select a.minYear, a.maxYear, a.id, b.type0value from
(select min(year) as minYear, max(year) as maxYear, id from table where id = 1 group by id) as a
inner join table as b on a.id = b.id
where b.type = 0
您的伪代码实际上非常接近。 您只需要条件聚合:
select ID,
min(case when type = 1 then year end) as MinYear,
max(case when type = 1 then year end) as MaxYear,
max(case when type = 0 then value end) as Type0Value
from table
group by ID;
如果可能有多个type = 0
行,则可能需要group_concat()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.