簡體   English   中英

MYSQL-僅將where子句應用於某些字段

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM