Search code examples
sqlsql-servert-sqlunionunion-all

T-SQL [UNION ALL] removing records from query result


Have a simple UNION ALL query marrying the results of two queries. The first query, run independently, returns 1208 records and the second 14. I would expect a properly syntaxed UNION ALL to return 1222 records but mine falls to 896.

Makes zero sense to me:

SELECT a.WBS_ELEMENT_ID as [WBS Element],
a.WBS_ELEMENT_DESC as [WBS Element Desc],
a.UHC_INDUSTRY as [Industry],
a.UHC_SECTOR as [Sector],
a.UHC_DUNS_NUMBER as [UHC DUNS Number],
a.UHC_DUNS_NAME as [UHC DUNS Name],
a.PRIORITY_SUB_SECTOR as [Priority Sub Sector],
a.BUDGET_ALLOCATION as [Budget Allocation],
a.LAST_UPDATED_ON as [Last Updated]
FROM DimSectorPd a
WHERE a.wbs_element_id is not null

UNION ALL

SELECT ROW_NUMBER() OVER (ORDER BY a.wbs_element_desc) as [WBS Element],
a.WBS_ELEMENT_DESC as [WBS Element name],
a.UHC_INDUSTRY as [Industry],
a.UHC_SECTOR as [Sector],
a.UHC_DUNS_NUMBER  as [UHC DUNS Number],
a.UHC_DUNS_NAME as [UHC DUNS Name],
a.PRIORITY_SUB_SECTOR as [Priority Sub Sector],
a.BUDGET_ALLOCATION as [Budget Allocation],
a.LAST_UPDATED_ON as [Last Updated]
from dimsectorpd a where a.WBS_ELEMENT_ID is null

Solution

  • Your queries should return all rows in the table. Unless the table changes between executions, the results from running the subqueries separately should be the same as from running them with the UNION ALL.

    As a note, if you want to simplify the query, then you can do:

    SELECT COALESCE(a.WBS_ELEMENT_ID,
                    ROW_NUMBER() OVER (PARTITION BY wbs_element_id ORDER BY a. wbs_element_desc)
                   ) as [WBS Element],
           a.WBS_ELEMENT_DESC as [WBS Element Desc],
           a.UHC_INDUSTRY as [Industry],
           a.UHC_SECTOR as [Sector],
           a.UHC_DUNS_NUMBER as [UHC DUNS Number],
           a.UHC_DUNS_NAME as [UHC DUNS Name],
           a.PRIORITY_SUB_SECTOR as [Priority Sub Sector],
           a.BUDGET_ALLOCATION as [Budget Allocation],
           a.LAST_UPDATED_ON as [Last Updated]
    FROM DimSectorPd a;