How to bucket a SQL server query

后端 未结 2 699
-上瘾入骨i
-上瘾入骨i 2021-01-26 12:00

I have the following table in SQL Server:

Date            Browser         Country         Time(ms)
----------------------------------------------------------
201         


        
2条回答
  •  悲&欢浪女
    2021-01-26 12:27

    The following will give you a single list which includes the country i.e. so it doesn't make each country a column. To make each a column you either have to do what Sticky-Bit has done, or you have to pivot - either way you have to handle each country individually (unless you build the pivot using dynamic SQL). But maybe your end user can use this list instead of needing a separate column?

    declare @MyTable table ([Date] date, Browser varchar(32), Country varchar(2), [Time] int)
    
    insert into @MyTable ([Date], Browser, Country, [Time])
      select '2019-05-06',      'Chrome',          'US',              1000
      union all select '2019-05-06',      'Chrome',          'US',              560
      union all select '2019-05-07',      'Firefox',         'JP',              2300
      union all select '2019-05-07',      'Edge',            'US',              1200
      union all select '2019-05-07',      'Chrome',          'JP',              3000
      union all select '2019-05-07',      'Chrome',          'JP',              3200
      union all select '2019-05-07',      'Chrome',          'JP',              2100
      union all select '2019-05-07',      'Firefox',         'US',              2200
    
    select Duration, Country, count(*)
    from (
      select *
        , CASE WHEN [Time] >= 0 AND [Time] < 1000 THEN '0 - 1s'
        WHEN [Time] >= 1000 AND [Time] < 2000 THEN '1 - 2s'
        WHEN [Time] >= 2000 AND [Time] < 3000 THEN '2 - 3s'
        ELSE '+3s' END Duration
        , CASE WHEN [Time] >= 0 AND [Time] < 1000 THEN 0
        WHEN [Time] >= 1000 AND [Time] < 2000 THEN 1
        WHEN [Time] >= 2000 AND [Time] < 3000 THEN 2
        ELSE 3 END DurationOrder
      from @MyTable
    ) X
    group by Duration, DurationOrder, Country
    order by DurationOrder, Country
    

提交回复
热议问题