Need Help with SQL Server Query

Member_2_7967119
Member_2_7967119 used Ask the Experts™
on
I have a SQL table DEPARTMENT_REQUISITION_REGISTRATION

DEPT, YEAR, REQUEST_NUMBER

101, 2017, '10117-112233'
101, 2017, '10117-112244'
101, 2017, '10117-112255'
101, 2017, '10117-112266'
201,2017, '20117-211111'
201, 2017, '20117-311111'
201, 2017, '20117-411111'
201, 2017, '20117-511111'
101, 2018, '10118-112233'
101, 2018, '10218-112244'

Output needs to be

DEPARTMENT, 2017 ,2018

101, 4, 2
201, 3, 0

where 4 is the count() of the records fetched for department 101 in the year 2017 and similarly 2 is the count() for dept 101 in the year 2018. Please help me with the sQL server script. Thanks in advance
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
PortletPaulEE Topic Advisor
Most Valuable Expert 2014
Awarded 2013

Commented:
You need a GROUP BY query, and one that uses "conditional aggregates" (basically that is an aggregate function like COUNT() where there is a case expression involved as well.

select 
    department
  , count(case when year = 2017 then 1 end) as [2017]
  , count(case when year = 2018 then 1 end) as [2018]
from yourtable
where year in (2017,2018)
group by 
    department

Open in new window


Note that the COUNT() function ignores NULLs so the above could also be written as:
select 
    department
  , count(case when year = 2017 then 1 else NULL end) as [2017]
  , count(case when year = 2018 then 1 else NULL end) as [2018]
from yourtable
where year in (2017,2018)
group by 
    department

Open in new window


some people will instead use SUM() even though they really only want a count, like this:
select 
    department
  , sum(case when year = 2017 then 1 else 0 end) as [2017]
  , sum(case when year = 2018 then 1 else 0 end) as [2018]
from yourtable
where year in (2017,2018)
group by 
    department

Open in new window

I prefer to use COUNT() as in my first or second examples above.

Author

Commented:
The Calendar year is not static and can changed based on the data in the tables column.
PortletPaulEE Topic Advisor
Most Valuable Expert 2014
Awarded 2013

Commented:
That requires "dynamic sql".

But often this is better done in a "presentation layer"
When you present this data to the end users are you doing this in a printed report or via a html page (for example)?
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

PortletPaulEE Topic Advisor
Most Valuable Expert 2014
Awarded 2013

Commented:
a dynamic sql approach to this looks like this (untested):
DECLARE @cols AS NVARCHAR(MAX)
DECLARE @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME([year])
            FROM yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

SET @query = 'SELECT department, ' + @cols + ' FROM
            (
                SELECT
                      [department]
                    , [year]
                 FROM table1
           ) sourcedata
            pivot
            (
                 count(*)
                FOR [departmnt] IN (' + @cols + ')
            ) p '

select @query -- use select to inspect the generated sql
--execute(@query) -- once satisfied that sql is OK, use execute

Open in new window

inspect the generated sql when trying to test/debug, once it is complete then use execute
EE Topic Advisor
Most Valuable Expert 2014
Awarded 2013
Commented:
DECLARE @cols AS NVARCHAR(MAX)
DECLARE @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME([year])
            FROM mytable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

SET @query = 'SELECT dept, ' + @cols + ' FROM
            (
                SELECT
                      [dept]
                    , [request_number]
                    , [year]
                 FROM mytable
           ) sourcedata
            pivot
            (
                 count([request_number])
                FOR [year] IN (' + @cols + ')
            ) p '

--select @query -- use select to inspect the generated sql
execute(@query) -- once satisfied that sql is OK, use execute
;   

Open in new window

           
see:  https://rextester.com/MAV42750

the generated SQL looks like this:
SELECT dept, [2017],[2018] FROM
            (
                SELECT
                      [dept]
                    , [request_number]
                    , [year]
                 FROM mytable
           ) sourcedata
            pivot
            (
                 count([request_number])
                FOR [year] IN ([2017],[2018])
            ) p

Open in new window

Author

Commented:
The sql generated code is throwing an exception.

Incorrect syntax near '*'.

Author

Commented:
The error message is
Msg 102, Level 15, State 1, Line 12
Incorrect syntax near '('.

count([request_number])
                FOR [year] IN ([2017],[2018])

Author

Commented:
I am using SQL server 2008R2. Will that be an issues as the scripts you are showing on https://rextester.com/MAV42750 is using SQL server 2014 and we see an output there
PortletPaulEE Topic Advisor
Most Valuable Expert 2014
Awarded 2013

Commented:
PortletPaulEE Topic Advisor
Most Valuable Expert 2014
Awarded 2013

Commented:
it would be very helpful in future if you state the version in your question, particularly as a version gets older (alreay 10 years old)

Author

Commented:
What a quick response. The Script works. Will also consider the suggestion for implementing using the presentation layer.

Author

Commented:
Just to let you know that it is working on SQL server 2008 R2. I also tested the script in sql server 2012 which we currently use . Thanks a ton.
PortletPaulEE Topic Advisor
Most Valuable Expert 2014
Awarded 2013

Commented:
Here is a different approach which cannot be version dependent, it uses good old fashioned conditonal aggregates like my first reply to this question - but dynamically:

DECLARE @SQL nvarchar(4000);

SELECT
      @SQL = 'SELECT DEPT, ' +
      STUFF((
            SELECT DISTINCT
                  ', COUNT(CASE WHEN [year] = ' + CAST([year] AS nvarchar) + ' THEN 1 END) AS ' + quotename([year]) 
            FROM mytable
            FOR xml PATH ('')
      )
      , 1, 2, '') + 'FROM mytable GROUP BY DEPT ORDER BY DEPT';

select @SQL;
execute (@SQL);

Open in new window

see: https://rextester.com/PRCF54668

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial