rivi10
MIS
- Dec 17, 2010
- 16
I was able to flatten a table (made rows into columns). However my output has NULLS. I want to have just one row for every document name.
I do not want to create Procedure or use a Cursor. I want to know can this still be done with a query.
Thanks for your help!
Table_1
ID(PK) DOC_ID DOC_VERSION NAME
Y1 ABC1234 2 DOC1
Y2 DEF5678 2 DOC1
Y3 ABC1234 1 DOC1
Y4 DEF5678 1 DOC1
Y5 ABC1234 3 DOC2
Y6 DEF5678 3 DOC2
Y7 ABC1234 2 DOC2
Y8 DEF5678 2 DOC2
Y9 ABC1234 1 DOC2
Y10 DEF5678 1 DOC2
Y11 ABC1234 1 DOC3
Y12 DEF5678 1 DOC3
Table_3
colID (PK)) VERSIONID PROPERTYID PTY
X1 ABC1234 PTYID1 Doc Code
X2 DEF5678 PTYID2 Doc Type
Table_2
ID NAME
PTYID1 doccode1
PTYID2
PTYID1 doccode2
PTYID2 pdfdocument
PTYID1 doccode3
PTYID2 pptdocument
SELECT MAX(TABLE_1.DOC_VERSION) as MAXV, TABLE_1.NAME AS DOCUMENT_NAME, CASE WHEN TABLE_2.NAME='Doc Code' THEN TABLE_3.PTY END DOCCODE, CASE WHEN TABLE_2.NAME='Doc Type' THEN TABLE_3.PTY END DOCTYPE,
FROM TABLE_3 INNER JOIN TABLE_1
ON TABLE_3.VERSIONID = TABLE_1.DOC_ID
INNER JOIN TABLE_2
ON TABLE_3.PROPERTYID = TABLE_2.ID
GROUP BY TABLE_1.NAME AS DOCUMENT_NAME,
CASE WHEN TABLE_2.NAME='Doc Code' THEN TABLE_3.PTY END,
CASE WHEN TABLE_2.NAME='Doc Type' THEN TABLE_3.PTY END
Output:
MAXV DOCUMENT_NAME DOCCODE DOCTYPE
2 DOC1 doccode1 NULL
2 DOC1 NULL
3 DOC2 doccode2 NULL
3 DOC2 NULL pdfdocument
1 DOC3 doccode3 NULL
1 DOC3 NULL pptdocument
Expected Output:
MAXV DOCUMENT_NAME DOCCODE DOCTYPE
2 DOC1 doccode1
3 DOC2 doccode2 pdfdocument
1 DOC3 doccode3 pptdocument
I do not want to create Procedure or use a Cursor. I want to know can this still be done with a query.
Thanks for your help!
Table_1
ID(PK) DOC_ID DOC_VERSION NAME
Y1 ABC1234 2 DOC1
Y2 DEF5678 2 DOC1
Y3 ABC1234 1 DOC1
Y4 DEF5678 1 DOC1
Y5 ABC1234 3 DOC2
Y6 DEF5678 3 DOC2
Y7 ABC1234 2 DOC2
Y8 DEF5678 2 DOC2
Y9 ABC1234 1 DOC2
Y10 DEF5678 1 DOC2
Y11 ABC1234 1 DOC3
Y12 DEF5678 1 DOC3
Table_3
colID (PK)) VERSIONID PROPERTYID PTY
X1 ABC1234 PTYID1 Doc Code
X2 DEF5678 PTYID2 Doc Type
Table_2
ID NAME
PTYID1 doccode1
PTYID2
PTYID1 doccode2
PTYID2 pdfdocument
PTYID1 doccode3
PTYID2 pptdocument
SELECT MAX(TABLE_1.DOC_VERSION) as MAXV, TABLE_1.NAME AS DOCUMENT_NAME, CASE WHEN TABLE_2.NAME='Doc Code' THEN TABLE_3.PTY END DOCCODE, CASE WHEN TABLE_2.NAME='Doc Type' THEN TABLE_3.PTY END DOCTYPE,
FROM TABLE_3 INNER JOIN TABLE_1
ON TABLE_3.VERSIONID = TABLE_1.DOC_ID
INNER JOIN TABLE_2
ON TABLE_3.PROPERTYID = TABLE_2.ID
GROUP BY TABLE_1.NAME AS DOCUMENT_NAME,
CASE WHEN TABLE_2.NAME='Doc Code' THEN TABLE_3.PTY END,
CASE WHEN TABLE_2.NAME='Doc Type' THEN TABLE_3.PTY END
Output:
MAXV DOCUMENT_NAME DOCCODE DOCTYPE
2 DOC1 doccode1 NULL
2 DOC1 NULL
3 DOC2 doccode2 NULL
3 DOC2 NULL pdfdocument
1 DOC3 doccode3 NULL
1 DOC3 NULL pptdocument
Expected Output:
MAXV DOCUMENT_NAME DOCCODE DOCTYPE
2 DOC1 doccode1
3 DOC2 doccode2 pdfdocument
1 DOC3 doccode3 pptdocument