简体   繁体   中英

T-SQL Crosstab count query

If have the following dataset:

在此处输入图像描述

... and I want to do a crosstab of sorts, counting the data against specific criteria eg:

Colour criteria : String contains "Blue", "Red", "Yellow" or "Green" (not case sensitive)

Type criteria : String contains "Car", "Lorry", or "Bus (not case sensitive)

... and I would like the result to look like the following:

在此处输入图像描述

Is there an SQL query that I can run on the original data to produce the result I'm looking for?

With conditional aggregation:

select c.colour,
  count(case when t.VehicleData like '%Car%' then 1 end) Car,
  count(case when t.VehicleData like '%Lorry%' then 1 end) Lorry,
  count(case when t.VehicleData like '%Bus%' then 1 end) Bus
from (
  select 'Blue' colour union all 
  select 'Red' union all
  select 'Yellow' union all
  select 'Green'
) c left join tbl1 t
on t.VehicleData like '%' + c.colour + '%'
group by c.colour

See the demo .
Results:

> colour | Car | Lorry | Bus
> :----- | --: | ----: | --:
> Blue   |   3 |     1 |   0
> Red    |   1 |     2 |   0
> Yellow |   0 |     1 |   1
> Green  |   0 |     0 |   2

You can use CROSS APPLY with conditional aggregation; CROSS APPLY simplifies the generation of the list of colours:

select c.colour,
  sum(case when v.VehicleData like '%Car%' then 1 else 0 end) Car,
  sum(case when v.VehicleData like '%Lorry%' then 1 else 0 end) Lorry,
  sum(case when v.VehicleData like '%Bus%' then 1 else 0 end) Bus
from vehicles v
cross apply (values ('Blue'), ('Red'), ('Yellow'), ('Green')
) AS c(colour)
where v.VehicleData like '%' + c.colour + '%'
group by c.colour

Output:

colour  Car Lorry   Bus
Blue    3   1       0
Red     1   2       0
Yellow  0   1       1
Green   0   0       2

Demo on dbfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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