Link to home
Start Free TrialLog in
Avatar of Member_2_7967119
Member_2_7967119

asked on

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
Avatar of PortletPaul
PortletPaul
Flag of Australia image

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.
Avatar of Member_2_7967119
Member_2_7967119

ASKER

The Calendar year is not static and can changed based on the data in the tables column.
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)?
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
ASKER CERTIFIED SOLUTION
Avatar of PortletPaul
PortletPaul
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The sql generated code is throwing an exception.

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

count([request_number])
                FOR [year] IN ([2017],[2018])
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
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)
What a quick response. The Script works. Will also consider the suggestion for implementing using the presentation layer.
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.
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