T-SQL [UNION ALL]从查询结果中删除记录

时间:2015-05-21 19:16:04

标签: sql sql-server tsql unions union-all

让一个简单的UNION ALL查询结合两个查询的结果。第一个查询,独立运行,返回1208条记录,第二条是14.我希望一个正确的语法UNION ALL返回1222条记录但是我的下降到896条。

对我没有任何意义:

http://localhost:8080/rest/test/status

3 个答案:

答案 0 :(得分:1)

您的查询应返回表中的所有行。除非表格在执行之间发生变化,否则分别运行子查询的结果应与使用UNION ALL运行它们的结果相同。

作为一个注释,如果您想简化查询,那么您可以这样做:

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;

答案 1 :(得分:0)

显然,您的语法没有任何问题,但是如果您想尝试一种不同的方法来让UNION ALLROW_NUMBER一起使用。这是:

;WITH q1
AS (
    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 b.WBS_ELEMENT_ID AS [WBS Element]   --just bring NULL values 
        ,b.WBS_ELEMENT_DESC AS [WBS Element name]
        ,b.UHC_INDUSTRY AS [Industry]
        ,b.UHC_SECTOR AS [Sector]
        ,b.UHC_DUNS_NUMBER AS [UHC DUNS Number]
        ,b.UHC_DUNS_NAME AS [UHC DUNS Name]
        ,b.PRIORITY_SUB_SECTOR AS [Priority Sub Sector]
        ,b.BUDGET_ALLOCATION AS [Budget Allocation]
        ,b.LAST_UPDATED_ON AS [Last Updated]
    FROM dimsectorpd b
    WHERE b.WBS_ELEMENT_ID IS NULL
    )
SELECT CASE 
        WHEN q1.[WBS Element] IS NULL
            THEN ROW_NUMBER() OVER (ORDER BY q1.WBS_Element_Desc)
        ELSE q1.[WBS Element]
        END [WBS_Element]
    ,q1.[WBS Element Desc]
    ,q1.Industry
    ,q1.Sector
    ,q1.[UHC DUNS Number]
    ,q1.[UHC DUNS Name]
    ,q1.[Priority Sub Sector]
    ,q1.[Budget Allocation]
    ,q1.[Last Updated]
FROM q1

答案 2 :(得分:0)

以下是一个简化示例,您可以看看它是否适用于您的服务器?

SELECT a.low AS [My ID], 
    a.name AS [My Letter]
FROM master..spt_values as a
WHERE low is not null

UNION ALL

SELECT ROW_NUMBER() OVER (ORDER BY a.name) AS [My ID],
    a.name AS [My Letter]
FROM master..spt_values as a
WHERE a.low is null

master..spt_values为我系统上的2515行......