Reputation: 120
I'm trying to make a Query that will return a set of Columns with Values, this is what I'm getting at the moment,
╔═══╦═══════════════╦═════════════╗
║ ║ProgramTypeName║ TypeAmount ║
╠═══╬═══════════════╬═════════════╣
║ 1 ║ Center ║ 4 ║
║ 2 ║ School ║ 2 ║
╚═══╩═══════════════╩═════════════╝
I'm getting the ProgramTypeName from a Table, while the TypeAmount, Count(ProgramTypeName).
I'm trying to get to this point,
╔═══╦═══════════════╦═════════════╗
║ ║Center ║ School ║
╠═══╬═══════════════╬═════════════╣
║ 1 ║ 4 ║ 2 ║
╚═══╩═══════════════╩═════════════╝
Any ideas on what I can do to achieve this?
@Indian This is the result I'm getting from your suggestion,
╔═══╦═══════════════╦═════════════╗
║ ║Center ║ School ║
╠═══╬═══════════════╬═════════════╣
║ 1 ║ NULL ║ NULL ║
║ 2 ║ NULL ║ NULL ║
║ 3 ║ NULL ║ 2 ║
╚═══╩═══════════════╩═════════════╝
When querying for the data normally I have this,
╔═══╦══════════╦═════════════╦════════╦════════════════╦═══════╗
║ ║License ║ ProgName ║ Id ║ProgramTypeName ║Amount ║
╠═══╬══════════╬═════════════╬════════╬════════════════╬═══════╣
║ 1 ║ 45871 ║ TestName ║ 1 ║ Center ║ 4 ║
║ 2 ║ 45871 ║ TestName ║ 1 ║ School ║ 4 ║
║ 3 ║ 45871 ║ TestName ║ 1 ║ Other ║ 2 ║
╚═══╩══════════╩═════════════╩════════╩════════════════╩═══════╝
Upvotes: 0
Views: 54
Reputation: 120
I was able to get it to work with this,
Select Max(Case When A.ProgName = 'Center' Then TypeAmount End) As Center,
Max(Case When A.ProgName = 'School' Then TypeAmount End) As School,
Max(Case When A.ProgName = 'Other' Then TypeAmount End) As Other
From T_Prog P Inner Join (Select ProgID,
ProgName,
Count(ProgName) As ProgAmount
From T_ProgType_Join PTJ Inner Join T_ProgramType PTJ On PT.ProgramTypeId = PT.ProgramTypeId
Where PTJ.ProgramId = @ProgID
Group by ProgName, ProgID) A On A.ProgID= P.ProgID
Where PTJ.ProgID= @ProgID
Upvotes: 1
Reputation: 93754
Use conditional Aggregate
will work in both Mysql
and Sql Server
select
max(case when ProgramTypeName = 'Center' then TypeAmount END) as Center
max(case when ProgramTypeName = 'School' then TypeAmount END) as School
From (select ProgramTypeName ,Count(ProgramTypeName) from x ...) A
Group by somecol
Upvotes: 2
Reputation: 69594
DECLARE @Table TABLE (ProgrameTypeName VARCHAR(20))
INSERT INTO @Table VALUES
('Central'),('Central'),('Central'),('Central')
,('School'),('School')
SELECT *
FROM @Table t
PIVOT (
COUNT(ProgrameTypeName)
FOR ProgrameTypeName
IN ([Central],[School])
)p
╔═════════╦════════╗
║ Central ║ School ║
╠═════════╬════════╣
║ 4 ║ 2 ║
╚═════════╩════════╝
Upvotes: 0