简体   繁体   English

如何使用 SQL select 语句实现此结果

[英]How can I achieve this result using SQL select statement

05214M  2   BRAKE PAD METAL EACH    1992    POLARIS 400 XC/ XCR 
05214M  2   BRAKE PAD METAL EACH    1991    POLARIS 400 XC/ XCR 

Hello given the data above I am trying to take all rows that have the same part number (05214M) and the same model (POLARIS 400 XC/ XCR) and create a title using the years and model.您好,鉴于上述数据,我正在尝试获取具有相同部件号 (05214M) 和相同型号 (POLARIS 400 XC/XCR) 的所有行,并使用年份和型号创建标题。

So I want the title for this one to be所以我希望这个标题是

BRAKE PAD METAL POLARIS 400 XC/ XCR 1991-1992

Is this possible using SQL?这可以使用 SQL 吗?

Use min max and group by使用 min max 和 group by

  select  model, concat( min(`year`) , '-', max(`year`))
  from  my_table 
  group by model

if you want a specific model you can use a where如果你想要一个特定的模型,你可以使用 where

  select  model, concat( min(`year`) , '-', max(`year`))
  from  my_table 
  where model = '05214M'
  group by model

If you want a different result for model with a single row and model with more then a rows you could use an union like this如果您想要具有单行的模型和具有更多行的模型的不同结果,您可以使用这样的联合

  select  model, concat( min(`year`) , '-', max(`year`))
  from  my_table 
  group by model
  having count(*)>1 
  union 
  select  model, `year`
  from  my_table 
  group by model
  having count(*) = 1 

If for some reason you can't use a group by you can also do this with a windowing function like this:如果由于某种原因你不能使用一个组,你也可以用这样的窗口函数来做到这一点:

SELECT model,
       CAST(min(year) over (partition by model order by year) as varchar(4)) + '-' +
       CAST(max(year) over (partition by model order by year) as varchar(4)) as Date_Range
FROM atable

use concat and group by使用 concat 和 group by

select concat(item,' ',model,' ',Min(year),'-',Max(year)) as title   
from Table_name   
group by sku;

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

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