SQL QUERY

I have the following employee table

Fiddle Link



I need the output in the following format. How do i achieve this ?



----------------------------------------------------------------------
State                  Manager List             Total
-------------------------------------------------------------------
SALES                   OH[2]; AL[2];CO[1]        5
MARKETING         OH[2];AL[1];CO[0]         3
FINANCE               OH[1];AL[1];CO[0]         2
HR                         OH[1];CO[1];AL[0]         2
INVENTORY          OH[2];AL[1];CO[1]        4
----------------------------------------------------------------
                      Total                                      16
------------------------------------------------------------------
Varshini SAsked:
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.

ste5anSenior DeveloperCommented:
Normalize your data..
0
Walter RitzelSenior Software EngineerCommented:
Best I can came with for now.
with tmp(statecode,citycode,DataItem,ManagerDesignation) as 
(
  select statecode
       , citycode
       , convert(varchar(100),LEFT(managerdesignation, CHARINDEX(';',managerdesignation+';')-1)) as dataitem
       , STUFF(managerdesignation, 1, CHARINDEX(';',managerdesignation+';'), '') as managerdesignation
  from employee
  union all
  select statecode
       , citycode
       , convert(varchar(100),LEFT(managerdesignation, CHARINDEX(';',managerdesignation+';')-1)) as dataitem
       , STUFF(managerdesignation, 1, CHARINDEX(';',managerdesignation+';'), '') as managerdesignation
  from tmp
  where managerdesignation > ''
 )
 , tmp_ord as (
      select DataItem, statecode, citycode
      from tmp)
select DataItem
     , STUFF((SELECT ',' + statecode FROM tmp_ord WHERE DataItem=Result.DataItem FOR XML PATH ('')),1,1,'') as ManagerList
     , count(1)
from tmp_ord Result
group by DataItem

Open in new window


And I believe is possible to have the result as  you want, but the complexity of the query will scale up. I dont think is worth it.
0
Walter RitzelSenior Software EngineerCommented:
Now, I got it:
with tmp(statecode,citycode,DataItem,ManagerDesignation) as 
(
  select statecode
       , citycode
       , convert(varchar(100),LEFT(managerdesignation, CHARINDEX(';',managerdesignation+';')-1)) as dataitem
       , STUFF(managerdesignation, 1, CHARINDEX(';',managerdesignation+';'), '') as managerdesignation
  from employee
  union all
  select statecode
       , citycode
       , convert(varchar(100),LEFT(managerdesignation, CHARINDEX(';',managerdesignation+';')-1)) as dataitem
       , STUFF(managerdesignation, 1, CHARINDEX(';',managerdesignation+';'), '') as managerdesignation
  from tmp
  where managerdesignation > ''
 )
 , tmp_ord as (
      select DataItem, statecode, citycode
      from tmp)
select DataItem
     , STUFF((SELECT ',' + statecode + '[' + convert(char(5),count(1)) + ']' FROM tmp_ord WHERE DataItem=Result.DataItem group by statecode FOR XML PATH ('')),1,1,'') as ManagerList
     , count(1)
from tmp_ord Result
group by DataItem

Open in new window

0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Varshini SAuthor Commented:
Walter Ritzel:  i need the output in the following format

SALES                   OH[2]; AL[2];CO[1]        5
MARKETING         OH[2];AL[1];CO[0]         3
FINANCE               OH[1];AL[1];CO[0]         2
HR                         OH[1];CO[1];AL[0]         2
INVENTORY          OH[2];AL[1];CO[1]        4

But when i execute your script i got the following output. (i need only one record for a department)


DataItem                                            ManagerList                   (No column name)
FINANCE                                                     OH [1]                               1
FINANCE:SALES                                        AL [1 ]                               1
HR                                                               OH [1 ]                               1
HR:SALES                                                CO [1 ]                               1
INVENTORY                                            CO [1 ],OH [1]               2
INVENTORY:SALES:MARKETING               AL [1 ]                              1
MARKETING                                           OH [1 ]                            1
marketing:inventory                            OH [1 ]                              1
SALES                                                     OH [2  ]                              2
0
Walter RitzelSenior Software EngineerCommented:
Because you did not have corrected your data.
You should normalize the delimiter character on the column managerdesignation: on the first row you are using ; but in the other rows you are using :
You should choose one of them and fix your data.
0
Walter RitzelSenior Software EngineerCommented:
By my comment above, I mean this:
create table employee (statecode char(3),citycode char(3),ManagerDesignation varchar(100))
insert into employee values ('OH','A1','SALES;MARKETING;FINANCE;HR;INVENTORY')
insert into employee values ('OH','A2','SALES')
insert into employee values ('OH','A3','marketing;inventory')

insert into employee values ('AL','A1','FINANCE;SALES')
insert into employee values ('AL','C1','INVENTORY;SALES;MARKETING')

insert into employee values ('CO','Z1','INVENTORY')
insert into employee values ('CO','Z3','HR;SALES')

Open in new window


Here is the Fiddle link with test data corrected and query working:
http://sqlfiddle.com/#!6/96f75/2
0
Varshini SAuthor Commented:
Walter:  Thank You. Now it is working well. I need to list my manager's list in descending order. Where do i use order by in this query ? Like
 INVENTORY   OH [2 ],CO[1],AL[1]
 MARKETING   OH[2],AL[1]
SALES               OK[2],AL[1]

And why it is not listing counts are 0 ?  CO[0]
0
Walter RitzelSenior Software EngineerCommented:
Here is with the order:
with tmp(statecode,citycode,DataItem,ManagerDesignation) as 
(
  select statecode
       , citycode
       , convert(varchar(100),LEFT(managerdesignation, CHARINDEX(';',managerdesignation+';')-1)) as dataitem
       , STUFF(managerdesignation, 1, CHARINDEX(';',managerdesignation+';'), '') as managerdesignation
  from employee
  union all
  select statecode
       , citycode
       , convert(varchar(100),LEFT(managerdesignation, CHARINDEX(';',managerdesignation+';')-1)) as dataitem
       , STUFF(managerdesignation, 1, CHARINDEX(';',managerdesignation+';'), '') as managerdesignation
  from tmp
  where managerdesignation > ''
 )
 , tmp_ord as (
      select DataItem, statecode, citycode
      from tmp)
select DataItem
     , STUFF((SELECT ',' + statecode + '[' + convert(char(5),count(1)) + ']' FROM tmp_ord WHERE DataItem=Result.DataItem group by statecode order by statecode desc FOR XML PATH ('')),1,1,'') as ManagerList
     , count(1)
from tmp_ord Result
group by DataItem

Open in new window


About the count of 0... In SQL, unless you want to work with hardcodes, you are not going to have counts of zero. That said, if those are the only 3 managers you have, you can create a query specific for each manager and union them.
I do not advise on that, as right now, we dont know the performance of the current query with a bigger database. Your sample data is very small to help us out on tunning.
0
Walter RitzelSenior Software EngineerCommented:
Here is with full list of managers (count = 0). It is generic, so it is good.
with tmp(statecode,citycode,DataItem,ManagerDesignation) as 
(
  select statecode
       , citycode
       , convert(varchar(100),LEFT(managerdesignation, CHARINDEX(';',managerdesignation+';')-1)) as dataitem
       , STUFF(managerdesignation, 1, CHARINDEX(';',managerdesignation+';'), '') as managerdesignation
  from employee
  union all
  select statecode
       , citycode
       , convert(varchar(100),LEFT(managerdesignation, CHARINDEX(';',managerdesignation+';')-1)) as dataitem
       , STUFF(managerdesignation, 1, CHARINDEX(';',managerdesignation+';'), '') as managerdesignation
  from tmp
  where managerdesignation > ''
 )
 , tmp_ord as (
      select DataItem, statecode, citycode
      from tmp)
select DataItem
     , STUFF((SELECT ',' + a.statecode + '[' + convert(varchar(5),count(b.statecode)) + ']' FROM (select distinct statecode from tmp_ord) a left join (select statecode from tmp_ord WHERE DataItem=Result.DataItem) b on a.statecode = b.statecode group by a.statecode order by a.statecode desc FOR XML PATH ('')),1,1,'') as ManagerList
     , count(1)
from tmp_ord Result
group by DataItem

Open in new window

0
Varshini SAuthor Commented:
Thank You, out put for SALES is not showing in order
SALES      OH [2 ],CO [1 ],AL [2 ]
0
Walter RitzelSenior Software EngineerCommented:
It is in descending order of manager or of counts? Right now is descending order of managers.
0
Walter RitzelSenior Software EngineerCommented:
Here is goes:
with tmp(statecode,citycode,DataItem,ManagerDesignation) as 
(
  select statecode
       , citycode
       , convert(varchar(100),LEFT(managerdesignation, CHARINDEX(';',managerdesignation+';')-1)) as dataitem
       , STUFF(managerdesignation, 1, CHARINDEX(';',managerdesignation+';'), '') as managerdesignation
  from employee
  union all
  select statecode
       , citycode
       , convert(varchar(100),LEFT(managerdesignation, CHARINDEX(';',managerdesignation+';')-1)) as dataitem
       , STUFF(managerdesignation, 1, CHARINDEX(';',managerdesignation+';'), '') as managerdesignation
  from tmp
  where managerdesignation > ''
 )
 , tmp_ord as (
      select DataItem, statecode, citycode
      from tmp)
select * from (      
select DataItem
     , STUFF((SELECT ',' + a.statecode + '[' + convert(varchar(5),count(b.statecode)) + ']' FROM (select distinct statecode from tmp_ord) a left join (select statecode from tmp_ord WHERE DataItem=Result.DataItem) b on a.statecode = b.statecode group by a.statecode order by a.statecode desc FOR XML PATH ('')),1,1,'') as ManagerList
     , count(1) as cnt
from tmp_ord Result
group by DataItem
) x
order by x.cnt desc

Open in new window

0
Varshini SAuthor Commented:
it is  descending order of count
0
Walter RitzelSenior Software EngineerCommented:
And now, with everything ordered:
with tmp(statecode,citycode,DataItem,ManagerDesignation) as 
(
  select statecode
       , citycode
       , convert(varchar(100),LEFT(managerdesignation, CHARINDEX(';',managerdesignation+';')-1)) as dataitem
       , STUFF(managerdesignation, 1, CHARINDEX(';',managerdesignation+';'), '') as managerdesignation
  from employee
  union all
  select statecode
       , citycode
       , convert(varchar(100),LEFT(managerdesignation, CHARINDEX(';',managerdesignation+';')-1)) as dataitem
       , STUFF(managerdesignation, 1, CHARINDEX(';',managerdesignation+';'), '') as managerdesignation
  from tmp
  where managerdesignation > ''
 )
 , tmp_ord as (
      select DataItem, statecode, citycode
      from tmp)
select * from (      
select DataItem
     , STUFF((SELECT ',' + a.statecode + '[' + convert(varchar(5),count(b.statecode)) + ']' FROM (select distinct statecode from tmp_ord) a left join (select statecode from tmp_ord WHERE DataItem=Result.DataItem) b on a.statecode = b.statecode group by a.statecode order by count(b.statecode) desc, a.statecode desc FOR XML PATH ('')),1,1,'') as ManagerList
     , count(1) as cnt
from tmp_ord Result
group by DataItem
) x
order by x.cnt desc

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
Varshini SAuthor Commented:
Thank You
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
Microsoft SQL Server 2008

From novice to tech pro — start learning today.