I have a query that is retrieving two columns to my results. I am using this query twice and putting these two queries together with a UNION ALL
, because for every record there should be another record but with a different values in the two columns where I am pre-setting values, depending on the value of one of my set columns.
I should have a column that has all the prices set as Debit
or Credit
, if the ExamType
is 6 then the prices should be set in a Credit
column, if the ExamType
is 2 then the prices should be set in Debit
.
If I run them individually it works fine but once I use union all
, I get a datatype error message. I have set these columns as NULLS but everything is under the Credit
column and the Debit
column is with null values. How can I fix this?
Example with short "invisible" string:
Select StudentID, ExamDate, 2 AS ExamType, '232-442' AS Account,Amounts AS Debit, '' AS Credit
From TableA
UNION ALL
Select StudentID, ExamDate, 6 AS ExamType, '832-446' AS Account, Amounts AS Credit, '' AS Debit
From TableA
ORDER BY 1
Example with NULL
Select StudentID, ExamDate, 2 AS ExamType, '232-442' AS Account,NULL AS Credit,Amounts AS Debit
From TableA
UNION ALL
Select StudentID, ExamDate, 6 AS ExamType, '832-446' AS Account, NULL AS Debit, Amounts AS Credit,
From TableA
ORDER BY 1
Final Results - How they should be:
StudentID ExamDate ExamType Account Debit Credit
1232111 8/9/2010 2 232-442 56.90
1232111 8/9/2010 6 832-446 56.90
4773923 7/5/2010 2 232-442 46.91
4773923 7/5/2010 6 832-446 46.91