• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 70
  • Last Modified:

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
------------------------------------------------------------------
0
Varshini S
Asked:
Varshini S
  • 9
  • 5
1 Solution
 
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
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
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
 
Varshini SAuthor Commented:
Thank You
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 9
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now