代码之家  ›  专栏  ›  技术社区  ›  ravsun

查询上次销售日期后1年内转售的商品

  •  2
  • ravsun  · 技术社区  · 7 年前

    我有一张表,上面有售出汽车的详细信息。其中一些汽车在过去1年、2年或3年内被转售。该表如下所示:

    Car_Type ||  Car_Reg_No  ||      Sold_Date    ||  Listing_No
     Hatch   ||     23789    ||  2017-02-03 11:26 ||  X6529
     Coupe   ||     16723    ||  2016-11-07 09:40 ||  N8156
     Sedan   ||     35216    ||  2016-05-23 10:34 ||  M8164
     Hatch   ||     23789    ||  2016-09-16 04:30 ||  O7361
    

    现在,我需要查询最新售出日期后1年内重新售出的记录(汽车)以及售出的次数。所以,我的输出如下:

    Car_Type ||  Car_Reg_No  ||  Sold_Count  || Latest_Sold_Date
     Hatch   ||     23789    ||      2       || 2017-02-03 11:26
    

    本质上,我如何在最新售出日期的特定时间范围内检查再售出记录?

    2 回复  |  直到 7 年前
        1
  •  1
  •   S3S    7 年前

    您可以通过查找最大值并根据您的条件加入来实现这一点。

    declare @TableA table (Car_Type varchar(64)
                          ,Car_Reg_No int
                          ,Sold_Date datetime
                          ,Listing_No varchar(6))
    
    insert into @TableA
    values
    insert into @TableA
    values
    ('Hatch',23789,'2017-02-03 11:26','X6529'),
    ('Coupe',16723,'2017-11-07 09:40','N8156'),
    ('Sedan',35216,'2017-05-23 10:34','M8164'),
    ('Hatch',23789,'2016-09-16 04:30','O7361'),
    ('Coupe',16723,'2014-11-07 09:40','N8156')
    
    ;with cte as(
    select
        Car_Type
        ,Car_Reg_No
        ,Latest_Sold_Date = max(Sold_Date)
    from
        @TableA
    group by 
        Car_Type
        ,Car_Reg_No)
    
    select 
        a.Car_Type
        ,a.Car_Reg_No
        ,Sold_Count = count(b.Listing_No) + 1
        ,a.Latest_Sold_Date
    from cte a
        inner join
        @TableA b on 
        b.Car_Reg_No = a.Car_Reg_No
        and b.Sold_Date != a.Latest_Sold_Date
        and datediff(day,b.Sold_Date,a.Latest_Sold_Date) < 366
        --if you want only cars which were sold within last year too, uncomment this
        --and datediff(day,a.Latest_Sold_Date,getdate()) < 366
    group by
        a.Car_Type
        ,a.Car_Reg_No
        ,a.Latest_Sold_Date
    
        2
  •  0
  •   Pugal    7 年前

    据我所知。。,

    select sd1.Car_Type, sd1.Car_Reg_No,
    count(sd1.Car_Reg_No) + 1 'no of sales in last one year', --1 is added because, see the last condition
    sd1.Sold_Date 'Last sold date'
    from(
    select *,ROW_NUMBER() over(partition by Car_Reg_No order by sold_date desc) as rn from #Table) as sd1
    join 
    (select * from #Table) as sd2
    on sd1.Car_Type = sd2.Car_Type 
    and DATEDIFF(dd,sd2.Sold_Date,sd1.Sold_Date) < 366
    and sd1.rn = 1 
    and sd1.Sold_Date <> sd2.Sold_Date -- here last sold is eliminated. so count is added by one.
    group by sd1.Car_Type,sd1.Sold_Date, sd1.Car_Reg_No
    order by sd1.Car_Reg_No