0

I have a table like this

SA_ID ---+---Acct_Id---+---SA_Type
101           111           TYPE1
102           111           TYPE2
103           112           TYPE1

I have a query to get acct_id having more than one sa_type

select acct_id,count(*) from sa_tbl
having count(*) > 1
group by acct_id;

I get a result like this

acct_id ---+---count(*)
111             2

But I need to get the result like this:

acct_id ---+---count(*)-----+sa_type1----+---sa_type2
    111             2        TYPE1            TYPE2

3 Answers3

2

I tried to get result like you mentioned in question but able to get something similar to this check it on SQL Fiddle

SELECT tbl.`Acct_Id` AS 'Acct_Id',COUNT(`Acct_Id`)  AS 'counts',
GROUP_CONCAT(`SA_Type`) AS 'types'
FROM `sa_tbl` AS tbl 
GROUP BY tbl.`Acct_Id` 
HAVING counts > 1

hope this will help you !

Ashish Jagtap
  • 2,799
  • 3
  • 30
  • 45
0

Check the pivot function, see question here MySQL pivot table

This function works for Oracle and MySQL. For other databases (if you need) you can check additionally by yourself.

Community
  • 1
  • 1
smnbbrv
  • 23,502
  • 9
  • 78
  • 109
0

If your RDBMS doesn't support PIVOT (as was already suggested to you), you can use a combination of MAX / CASE / GROUP BY:

select 
  acct_id,
  max((case when sa_type = 'TYPE1' then sa_id else NULL end)) as type1,
  max((case when sa_type = 'TYPE2' then sa_id else NULL end)) as type2
from sa_tbl
group by acct_id

Output:

acct_id type1   type2
112     103 
111     101     102

SQL Fiddle

Frank Schmitt
  • 30,195
  • 12
  • 73
  • 107