SQL Union子查询唯一ID - 返回双重结果

时间:2017-01-16 03:19:08

标签: sql subquery union unique-key

我正在使用此查询创建视图。此查询有效,但是从每个联合表返回的每个值都会产生2行。我如何获得1排?

ROW_NUMBER() OVER (ORDER BY A.ID) AS ID部分是因为我需要一个唯一的ID。 (这是更好的方法吗?)

SELECT Row_number()
       OVER (
         ORDER BY A.ID) AS ID,
       ALIAS_CKT_ID,
       peg_site_id,
       circuit_id,
       LOC_A_ADDRESS,
       CKT_ORDER,
       CKT_STATUS,
       PROD_DESCRIPTION,
       customer_code,
       CUSTOMER_ID,
       CUSTOMER_NAME,
       CKT_LOCATION_Z,
       network,
       market,
       Source
FROM   (SELECT circ.id,
           NULL                  AS 'ALIAS_CKT_ID',
           peg_site_id,        
           circuit_id            AS 'CIRCUIT_ID',
           NULL                  AS 'LOC_A_ADDRESS',
           NULL                  AS 'CKT_ORDER',
           NULL                  AS 'CKT_STATUS',
           NULL                  AS 'PROD_DESCRIPTION',
           circ.customer_code,  
           NULL                  AS 'CUSTOMER_ID',
           cust.company          AS 'CUSTOMER_NAME',
           NULL                  AS 'CKT_LOCATION_Z',
           network,
           Cast(circ.market AS VARCHAR(max)) AS market,
           'PEG'                             AS 'Source'
    FROM   dbo.peg_circuit_network_data circ
           LEFT JOIN dbo.peg_customers cust
                  ON cust.customer_code = circ.customer_code
    UNION ALL
    SELECT cv.id,
           ALIAS_CKT_ID,
           CKT_LOCATION_Z   AS 'peg_site_id',
           CIRCUIT_ID,
           LOC_A_ADDRESS,
           CKT_ORDER,
           CKT_STATUS,
           PROD_DESCRIPTION,
           cv.CUSTOMER_CODE AS customer_code,
           CUSTOMER_ID,
           cust.company     AS 'CUSTOMER_NAME',
           CKT_LOCATION_A,
           NULL             AS 'network',
           NULL             AS 'market',
    FROM   dbo.tc_cv_circuit_network cv
           LEFT JOIN dbo.peg_customers cust
                  ON cust.customer_code = cv.customer_code
    UNION ALL
    SELECT NULL               AS 'id',
           NULL               AS 'ALIAS_CKT_ID',
           a_peg_site_id      AS 'peg_site_id',
           peg_circuit_id     AS 'CIRCUIT_ID',
           a_address          AS 'LOC_A_ADDRESS',
           NULL               AS 'CKT_ORDER',
           order_status       AS 'CKT_STATUS',
           product_type       AS 'PROD_DESCRIPTION',
           customer_code      AS customer_code,
           NULL               AS CUSTOMER_ID,
           customer_short     AS 'CUSTOMER_NAME',
           NULL               AS CKT_LOCATION_A,
           NULL               AS 'network',
           Cast(market AS VARCHAR(max)) AS market,
    FROM   Openquery(crltoolsp01, 
LEFT JOIN crm ON cpm.customer_short=crm.company
WHERE cpm.product_type="Dark Fiber";')) A 

1 个答案:

答案 0 :(得分:0)

尝试使用SELECT DISTINCT代替SELECT

联合查询默认生成不同的行;添加DISTINCT会改变这种情况。