Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Multiple Groups of Data in SQLServer

Tags:

sql-server

Been scratching my head on this one, but I feel I'm overlooking the obvious answer, and none of my search phrases have lead to any results.. I am compiling the results of a survey in a database, in the following structure.

ID  TestName     Q1    Q2    Q3    Q4
--  ---------  ----  ----  ----  ----
1   test1        1     2     1     1
2   test1        2     3     4     1
3   test2        1     1     4     2
4   test1        2     5     3     4
5   test2        1     5     2     4

I want to group the similar results in each column, only if they have they share the same Name, and get a count from each similar result. My final output is shown below, but I am trying to find out how to write the query without having 4 separate queries.

Test 1
        Question 1 Results
        1(1)
        2(2)
        3(0)
        4(0)
        5(0)

        Question 2 Results
        1(0)
        2(1)
        3(1)
        4(0)
        5(1)

        Question 3 Results
        1(1)
        2(0)
        3(1)
        4(1)
        5(0)

        Question 4 Results
        1(2)
        2(0)
        3(0)
        4(1)
        5(0)

Test 2
        Question 1 Results
        1(2)
        2(0)
        3(0)
        4(0)
        5(0)

        Question 2 Results
        1(1)
        2(0)
        3(0)
        4(0)
        5(1)

        Question 3 Results
        1(0)
        2(1)
        3(0)
        4(1)
        5(0)

        Question 4 Results
        1(0)
        2(1)
        3(0)
        4(1)
        5(0)
like image 672
Patcouch22 Avatar asked Aug 05 '26 22:08

Patcouch22


1 Answers

declare @YourTable table (
    id int,
    TestName varchar(10),
    q1 char(1),
    q2 char(1),
    q3 char(1),
    q4 char(1)
)

insert into @YourTable
    (id, TestName, q1, q2, q3, q4)
    select 1,'test1','1','2','1','1' union all
    select 2,'test1','2','3','4','1' union all
    select 3,'test2','1','1','4','2' union all
    select 4,'test1','2','5','3','4' union all
    select 5,'test2','1','5','2','4'

select TestName, 
       sum(case when q1 = '1' then 1 else 0 end) as [q1(1)],
       sum(case when q1 = '2' then 1 else 0 end) as [q1(2)],
       /* ... */
       sum(case when q4 = '4' then 1 else 0 end) as [q4(4)],      
       sum(case when q4 = '5' then 1 else 0 end) as [q4(5)]
    from @YourTable
    group by TestName
like image 123
Joe Stefanelli Avatar answered Aug 07 '26 17:08

Joe Stefanelli