0

I want the data in a particular format as grouping on one column it will display its result into rows and also grouping another column and display result in rows corresponding to that grouping of rows.

The data is in the format :

id  type    insertdate             forUser
------------------------------------------
1   Suit    2020-08-24 13:16:42.000 sw
2   Suit    2020-08-24 13:16:49.000 sw
3   Suit    2020-08-24 00:46:31.773 sw
4   jacket  2020-08-24 13:17:15.000 sw
5   jacket  2020-08-24 13:17:35.000 sw
6   jacket  2020-08-24 00:47:43.620 sw
7   jacket  2020-08-24 00:48:42.470 SK
8   Blazer  2020-08-24 13:19:19.000 SK
9   Blazer  2020-08-24 00:49:00.097 SK
10  Blazer  2020-08-24 00:49:07.130 SK
11  Blazer  2020-08-24 13:20:34.000 SK
12  indo    2020-08-24 13:21:15.000 SK
13  indo    2020-08-24 13:21:46.000 SK
14  indo    2020-08-24 13:21:59.000 SK

and I want the result in this format :

forUser suit jacket blazer indo
--------------------------------
SK      0     1     4       3
sw      3     3     0       0

I have no idea how to achieve it, can we use count with where clause:

select forUser, count(* where type='suit') 
from tblTurnSys
group by forUser
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Juned Khan
  • 1
  • 1
  • 5
  • This technique of turning rows into columns is called a [pivot](https://www.sqlservertutorial.net/sql-server-basics/sql-server-pivot/). – SMor Aug 24 '20 at 15:25

1 Answers1

2

You can use conditional aggregation:

select forUser,
       sum(case when type = 'suit' then 1 else 0 end) as suit,
       sum(case when type = 'jacket' then 1 else 0 end) as jacket,
       sum(case when type = 'blazer' then 1 else 0 end) as blazer,
       sum(case when type = 'indo' then 1 else 0 end) as indo
from t
group by forUser;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786