我在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语法。我该怎么做?
答案 0 :(得分:3)
奇怪的表结构,但是:
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;
答案 1 :(得分:0)
你应该使用内部联接。 一半将处理最小值和最大值,后半部分将处理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
答案 2 :(得分: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()
代替。