Need Help with SQL Server Query

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
Member_2_7967119Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

PortletPaulEE Topic AdvisorCommented:
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.
0
Member_2_7967119Author Commented:
The Calendar year is not static and can changed based on the data in the tables column.
0
PortletPaulEE Topic AdvisorCommented:
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)?
0
10 Tips to Protect Your Business from Ransomware

Did you know that ransomware is the most widespread, destructive malware in the world today? It accounts for 39% of all security breaches, with ransomware gangsters projected to make $11.5B in profits from online extortion by 2019.

PortletPaulEE Topic AdvisorCommented:
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
0
PortletPaulEE Topic AdvisorCommented:
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

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Member_2_7967119Author Commented:
The sql generated code is throwing an exception.

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

count([request_number])
                FOR [year] IN ([2017],[2018])
0
Member_2_7967119Author 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
0
PortletPaulEE Topic AdvisorCommented:
0
PortletPaulEE Topic AdvisorCommented:
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)
0
Member_2_7967119Author Commented:
What a quick response. The Script works. Will also consider the suggestion for implementing using the presentation layer.
0
Member_2_7967119Author 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.
0
PortletPaulEE Topic AdvisorCommented:
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
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
SQL

From novice to tech pro — start learning today.