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
Microsoft SQL ServerSQL

Avatar of undefined
Last Comment
PortletPaul

8/22/2022 - Mon
PortletPaul

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

ASKER
The Calendar year is not static and can changed based on the data in the tables column.
PortletPaul

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)?
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
PortletPaul

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
PortletPaul

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Member_2_7967119

ASKER
The sql generated code is throwing an exception.

Incorrect syntax near '*'.
Member_2_7967119

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

count([request_number])
                FOR [year] IN ([2017],[2018])
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Member_2_7967119

ASKER
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
PortletPaul

PortletPaul

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)
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Member_2_7967119

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

ASKER
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.
PortletPaul

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
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.