SQL INSERT ISSUE与CTE

时间:2016-02-04 20:58:56

标签: sql sql-server tsql

我正在处理以下查询。目标是插入符合where子句中条件的[AppID]和随机选择的[ufid],而不插入重复项。我已经研究过TABLESAMPLE和Random(),但无法弄清楚这一点。

例如:#mult_nuf表有4条记录,AppID = 123456,Major =' GEBOX'。 #temp_rUF将在表格中包含ufid =' UF7'和sh_plan =' GEBOX'。我需要将[App_ID]和另一个[sh_plan]的[ufid]插入到临时表中,其中[Major]和[sh_plan]不相同。到目前为止,每个[ufid]的记录都插入了相同的[Appid]。我在表中有45 [ufid},因此临时表有相同[AppID]的45条记录。对于[AppID]只有4个随机[ufid] ..

的记录

mult_nuf表

AppID              Major
004540036          GEBOX
004540036          GEBOX
004540036          GEBOX
004540036          GEBOX

#temp_ruf表

ufID                  sh_Plan
U1                    GECCE
U2                    REDSG
U5                    GFRTY
U7                    GEBOX
U8                    JKIUTY

示例输出应该看起来像

App_ID              ufID
004540036              U1
004540036              U2
004540036              U5
004540036              U8

查询我正在使用

WITH Match_NomineesWithReviewers AS
(
    SELECT DISTINCT 
        [AppID], 
        RTRIM(Major) AS Major
    FROM  
        #mult_nuf
)
SELECT 
    m.[AppID], 
    r.ufid
INTO 
    #TempNTable
FROM 
    Match_NWithR m
CROSS APPLY 
    (SELECT ir.ufid
     FROM #temp_rUF ir
     WHERE m.Major <> ir.sh_plan) r

2 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情。如果appid都是相同的,它应该有效。

INSERT INTO ATempTable
SELECT TOP (SELECT COUNT(1) FROM mult_nuf) Appid,
  ufID
FROM
    (SELECT DISTINCT *
    FROM mult_nuf
    CROSS JOIN temp_ruf
    WHERE major <> sh_plan) BaseQuery
ORDER BY NEWID()

答案 1 :(得分:0)

假设您想在一组AppID上执行此操作,我会使用ROW_NUMBER和ORDER BY newid()随机,然后限制前4个结果,如下所示:

WITH Match_NomineesWithReviewers AS
(
    SELECT 
        [AppID], 
        RTRIM(Major) AS Major
    FROM  
        #mult_nuf
    GROUP BY
        [AppID], 
        RTRIM(Major)
)
, rownum_matches AS (
SELECT 
    m.[AppID], 
    r.ufid,
    ROW_NUMBER() OVER (PARTITION BY m.[AppID] ORDER BY newid()) AS rownum
FROM 
    Match_NomineesWithReviewers m
JOIN
    #temp_rUF t ON t.sh_Plan != m.Major
 )
 SELECT [AppID], ufid FROM rownum_matches WHERE rownum <= 4

如果您需要它以匹配原始记录数,可能是这样的:

WITH Match_NomineesWithReviewers AS
(
    SELECT 
        [AppID], 
        RTRIM(Major) AS Major,
        COUNT(1) AS rowcnt
    FROM  
        #mult_nuf
    GROUP BY
        [AppID], 
        RTRIM(Major)
)
, rownum_matches AS (
SELECT 
    m.[AppID], 
    r.ufid,
    m.rowcnt,
    ROW_NUMBER() OVER (PARTITION BY m.[AppID] ORDER BY newid()) AS rownum
FROM 
    Match_NomineesWithReviewers m
JOIN
    #temp_rUF t ON t.sh_Plan != m.Major
 )
SELECT [AppID], ufid FROM rownum_matches rm WHERE rownum <= rowcnt