SQL查询以选择具有两个或更多相同列的行

时间:2019-05-20 21:18:34

标签: mysql sql sorting duplicates

我有餐桌供应商

    line    name     country    supplier     city
    1        A         UK         Google     London
    1        A         UK         Apple      London
    1        A         UK         Amazon     London
    2        B         UK         Microsoft  London
    3        C         UK         Amazon     London
    4        D         UK         Google     Oxford
    4        D         UK         Apple      Oxford
    4        D         UK         Amazon     Oxford

我正在寻找一个案例声明,以防万一同一行号出现多次,它将选择一个特定的供应商,在此示例中,当城市为伦敦时选择“ Google”,否则为城市为牛津并选择同一行出现不止一次,它将选择供应商“亚马逊”

预期结果

    line    name     country    supplier     city
    1        A         UK         Google     London
    2        B         UK         Microsoft  London
    3        C         UK         Amazon     London
    4        D         UK         Amazon     Oxford

3 个答案:

答案 0 :(得分:0)

您可以使用以下查询

<SeekBarPreference
            app:key="seekRounds"
            android:title="Number of rounds"
            android:summary="This is the summary"
            android:max="2"
            app:showSeekBarValue="true"
            android:progress="0"
            android:theme="@style/Base.Widget.AppCompat.SeekBar"
        />

Demo

答案 1 :(得分:0)

您可以使用相关子查询:

select t.*
from t
where (supplier, city) = (select t2.supplier, t2.city
                          from t t2
                          where t2.line = t.line  -- and perhaps other conditions as well
                          order by (case when (supplier, city) in ('Google', 'London') then 1
                                         when (supplier, city) in ('Amazon', 'Oxford') then 1
                                         else 3
                                    end)
                          limit 1
                         );

您可以随时为order by子句添加更多优先级条件。

答案 2 :(得分:0)

将表联接到一个查询,该查询由您放置条件的行组成,然后按行,名称,国家/地区和城市分组:

select 
  t.line,
  t.name,
  t.country,
  coalesce(max(u.supplier), max(t.supplier)) supplier,
  t.city
from tablename t left join (
  select 'Google' supplier, 'London' city 
  union all 
  select 'Amazon', 'Oxford'
) u on u.supplier = t.supplier and u.city = t.city 
group by t.line, t.name, t.country, t.city

请参见demo
结果:

> line | name | country | supplier  | city  
> ---: | :--- | :------ | :-------- | :-----
>    1 | A    | UK      | Google    | London
>    2 | B    | UK      | Microsoft | London
>    3 | C    | UK      | Amazon    | London
>    4 | D    | UK      | Amazon    | Oxford
相关问题