简体   繁体   English

与 group by 结合使用时的 SQL 案例

[英]SQL case when combined with group by

lets say I have a table with 2 columns: car_id, and selling_code假设我有一个包含 2 列的表:car_id 和 sell_code

  • if a car got sold at 2020, no matter how many times, it will have a single line in the table with the code 1.如果一辆汽车在 2020 年售出,无论多少次,它都会在表中出现一行代码为 1。

  • if a car got sold at 2019, no matter how many times, it will have a single line in the table with the code 2.如果一辆汽车在 2019 年售出,无论多少次,它都会在表格中出现一行代码为 2。

  • if it got sold both at 2019 and 2020, it will have 2 lines, one with code 1 and one with code 2.如果它在 2019 年和 2020 年都售出,它将有 2 行,一行代码为 1,另一行代码为 2。

I want to create from this table a new table, in which there is only a single line for each id, and 2 columns: car_id and selling_text.我想从这个表中创建一个新表,其中每个 id 只有一行,以及 2 列:car_id 和 sell_text。 if the car got sold only at 2020, the selling_text is '2020' else if the car got sold only at 2019, the selling_text is '2019' and if it got sold both at 2020 and 2019, the selling_text is 'both'如果汽车仅在 2020 年出售,则销售文本为“2020”,否则如果汽车仅在 2019 年出售,则销售文本为“2019”,如果汽车在 2020 年和 2019 年均出售,则销售文本为“两者”

select car_id,
       case when count(distinct selling_code) = 2 then 'both'
            when max(selling_code) = 1 then '2020'
            else '2019'
       end as selling_text
from your_table
group by car_id

Hmmm .嗯。 . . . . you seem to want:你似乎想要:

select distinct car_id, year,
       (case when year = 2019 then 1 when year = 2020 then 2 end)
from t
where year in (2019, 2020);

This assumes that you actually have a year in the table.这假设您实际上在表中有一年。 Although the question suggests that this is in the data, the question also explicitly describes the table with no such column.尽管问题表明这是在数据中,但该问题还明确描述了没有此类列的表。

If you want to be fancy, you can also use:如果你想花哨,你也可以使用:

select distinct car_id, year, year - 2018 as code
from t
where year in (2019, 2020);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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