简体   繁体   中英

MYSQL - apply a where clause to only some fields

I have this table in 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

I want to select the minimum and maximum year for each person (IDs 1 and 2), but I also want to select the value associated with type 0 for each person as well. Ideally this is what the query result would look like:

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

The query should look, I think, something like this...

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

But this is obviously not correct SQL syntax. How do I do this?

strange table structure, but:

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;

you should use inner join. one half will handle the min and max, second half the type0value:

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 

Your pseudo-code is actually pretty close. You just need conditional aggregation:

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;

If there could be multiple rows with type = 0 , you might want group_concat() instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM