Click here to Skip to main content
15,888,401 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have tables like this

Table1

Cid	FlagId	AdjusterId
1	1	1
2	2	2
3	1	1
4	3	2
5	4	1
6	2	1

Table2

FlagId	FlagName
1	F1        
2	F2        
3	F3        
4	F4       

Table3

AId	AName
1	ABC       
2	XYZ


I need output as below

AName	F1	F2   F3   F4
ABC	2	1    0    1
XYZ	0	1    1    0


What I have tried:

Is it achievable with pivot.

SQL
WITH PIVOTED
AS (
	SELECT *
	FROM Claim c
	inner join Flag f on f.flagId = c.FlagId
		PIVOT(Sum(f.FlagId)  
			FOR f.FlagName IN([F1], [F2],[F3],[F4]) 
		) P
)
SELECT 
	*
FROM PIVOTED


I am not getting result as expected
Posted
Updated 20-Mar-18 19:25pm
v3

Check this:
SQL
SELECT AName, [F1], [F2], [F3], [F4]
FROM (
	SELECT t2.FlagName, t3.AName 
	FROM @Table1 AS t1
		INNER JOIN @Table2 AS t2 ON t1.FlagId = t2.FlagId  
		INNER JOIN @Table3 AS t3 ON t1.AdjusterId = t3.AId 
	) AS DT 
PIVOT(COUNT(FlagName) FOR FlagName IN ([F1], [F2], [F3], [F4])) AS PVT

Result:
AName   F1      F2      F3     F4
ABC     2	    1	    0	    1
XYZ	    0	    1	    1	    0


Note: Replace @Table1, @Table2, @Table3 with proper table name.


For further details, please see:
Using PIVOT and UNPIVOT | Microsoft Docs[^]
Visual Representation of SQL Joins[^]
 
Share this answer
 
Comments
Animesh Datta 7-Mar-18 0:26am    
My 5! Sir
Maciej Los 7-Mar-18 2:00am    
Thank you
I have not used PIVOT, however it can be done using derived, temp table or table variable etc.. Below is using derived table:

SELECT AId, SUM(Derived.F1) AS F1,SUM(Derived.F2) AS F2,SUM(Derived.F3) AS F3 ,SUM(Derived.F4) AS F4 FROM 
(
SELECT T3.AID,
CASE FName WHEN 'F1' THEN COUNT(1)  ELSE 0 END AS F1,
CASE FName WHEN 'F2' THEN COUNT(1)  ELSE 0 END AS F2,
CASE FName WHEN 'F3' THEN COUNT(1)  ELSE 0 END AS F3,
CASE FName WHEN 'F4' THEN COUNT(1)  ELSE 0 END AS F4
 FROM TABLE2 T2 INNER JOIN TABLE1 T1 ON T2.FId = T1.FId INNER JOIN TABLE3 T3 ON T1.AId = T3.AId
GROUP BY T3.AID, FName
) Derived GROUP BY AID


Hope this helps.. Enjoy coding :)
 
Share this answer
 
how i create a student attendence list in sql out attendence give win student touch the thumb impression;
 
Share this answer
 
Comments
Maciej Los 21-Mar-18 3:09am    
This is not an answer. Please, delete it. If you want to post a question, please ASK

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900