I have two select statements . I want to combine the results of these two select statements.
I tried UNION and I am getting this error "Conversion failed when converting the varchar value 'n' to data type int".
Is there any way I can combine these two statements.
Below are the two statements:
SELECT Descr,FilterA,FilterB,FilterC,CreateDate from X JOIN Y on Y_ID = X_ID WHERE Label IN ('111','222','333')
'
SELECT Label, COUNT(Label), FROM X JOIN Y on Y_ID = X_ID WHERE CreateDate >= DATEADD(day, -7, GETDATE()) AND Label IN ('111','222','333')
GROUP BY Label
Union requires that all datatypes between the two selects are compatible. ALso, the number of columns must match. (They don't in your example). I suspect that FilterA is not an integer. To fix the union you could, in the second select, write
SELECT Label, CAST(COUNT(Label) as varchar(10)) , null, null, null
Yes as you have mentioned FilterA is not an integer.
I have made the following changes to the statements
SELECT Descr, FilterA, FilterB, FilterC, CreateDate , null, null from X JOIN Y on Y_ID = X_ID WHERE Label IN ('111','222','333')
UNION ALL
SELECT Label, CAST(COUNT(Label ) as varchar(10)) AS N ,null,null,null,null FROM X JOIN Y on Y_ID = X_ID WHERE CreateDate >= DATEADD(day, -7, GETDATE()) AND Label IN ('111','222','333')
GROUP BY Label
When I do this it is returning NULL for both the columns Label and N (which is the count of label)
SELECT Descr, FilterA AS N, FilterB, FilterC, CreateDate , null AS XYZ, null AS ZYX
from X JOIN Y on Y_ID = X_ID
WHERE Label IN ('111','222','333')
UNION ALL
SELECT Label, CAST(COUNT(Label ) as varchar(10)) AS N ,null,null,null,null,null
FROM X JOIN Y on Y_ID = X_ID
WHERE CreateDate >= DATEADD(day, -7, GETDATE()) AND Label IN ('111','222','333')
GROUP BY Label
By-the-way please use the </> to format your code.
SELECT Descr, FilterA AS N, FilterB, FilterC, CreateDate , null AS XYZ, null AS ZYX
from X JOIN Y on Y_ID = X_ID
WHERE Label IN ('111','222','333')
UNION ALL
SELECT Label, CAST(COUNT(Label ) as varchar(10)) AS N ,null,null,null,null,null
FROM X JOIN Y on Y_ID = X_ID
WHERE CreateDate >= DATEADD(day, -7, GETDATE()) AND Label IN ('111','222','333')
GROUP BY Label
SELECT Descr
, FilterA AS N
, FilterB
, FilterC
, CreateDate
, NULL AS XYZ
, NULL AS ZYX
FROM X
INNER JOIN Y
ON Y_ID = X_ID
WHERE Label IN ('111', '222', '333')
UNION ALL
SELECT Label
, CAST(COUNT(Label) AS VARCHAR(10)) AS N
, NULL
, NULL
, NULL
, NULL
, NULL
FROM X
INNER JOIN Y
ON Y_ID = X_ID
WHERE CreateDate > DATEADD(day, - 7, GETDATE())
AND Label IN ('111', '222', '333')
GROUP BY Label