Showing posts with label Display Different Values In Respective Columns. Show all posts
Showing posts with label Display Different Values In Respective Columns. Show all posts

Thursday, May 1, 2008

Display Different Values In Respective Columns

I haven’t updated my blog for quite long time. But today I’ve times to post some information related to the SQL query. When I prepare reports for one of the hospital in Myanmar, I’m facing some difficulties to display data and raised question in Experts-Exchange. This post is my re-collection of solutions from Experts-Exchange. And also thanks for the expert, angellll, who answer this solution for me. The problem is as follow:

I’ve one query which join 3 tables and produce different values in 2 columns.
Table A Contain (ID,SubID)
Data for Table A as example:
ID, SubID
1, 1
2, 7

Table B Contain (ID, Values)
Data for Table B as example:
ID, Values
1, 1000
2, 2500

Table C Contain (ID, SubID, Values)
Data for Table C as example:
ID, SubID, Values
1, 1, 100
1, 2, 150
1, 3, 20
2, 5, 0
2, 7, 150

I want to display as follow
ID, SubID, ID Values, SubID Values
1, 1, 1000, 100
1, 2, 0, 150
1, 3, 0, 20
2, 5, 0, 0
2, 7, 2500, 150

The solution for this problem is as follow:
SELECT a.id, a.subid, COALESCE(b.values,0) as [id values]
FROM tableA a
JOIN tableB b
ON a.ID = b.ID
RIGHT JOIN tableC c
ON c.id = a.id
AND c.subid = a.subid