从多组记录中查找entryno集

时间:2017-11-04 05:27:53

标签: sql sql-server tsql

我有两个SQL临时表#Temp1#Temp2

我想得到entryno,其中包含一组临时表。

例如:#Temp2有8条记录。我想在#Temp1中搜索,其中包含#Temp1的一组记录。

CREATE TABLE #Temp1 (entryNo INT, setid INT, measurid INT,measurvalueid int)

CREATE TABLE #Temp2(setid INT, measurid INT,measurvalueid int)

INSERT INTO #Temp1 (entryNo,setid,measurid,measurvalueid ) 

VALUES  (1,400001,1,1),                                                        
        (1,400001,2,110),
        (1,400001,3,1001),
        (1,400001,4,1100),
        (2,400002,5,100),
        (2,400002,6,102),
        (2,400002,7,1003),
        (2,400002,8,10004),
        (3,400001,1,1),
        (3,400001,2,110),
        (3,400001,3,1001),
        (3,400001,4,1200)

INSERT INTO #Temp2 (setid,measurid,measurvalueid ) 

    VALUES (400001,1,1),
           (400001,2,110),
           (400001,3,1001),
           (400001,4,1100),
           (400002,5,100),
           (400002,6,102),
           (400002,7,1003),
           (400002,8,10004)

我想要输出

EntryNo
   1
   2

它包含两组。

一个是:

  (400001,1,1),
  (400001,2,110),
  (400001,3,1001),
  (400001,4,1100) 

第二个是:

  (400002,5,100),
  (400002,6,102),
  (400002,7,1003),
  (400002,8,10004) 

1 个答案:

答案 0 :(得分:0)

试试这个:

WITH DataSourceInialData AS
(
    SELECT *
          ,COUNT(*) OVER (PARTITION BY [entryNo], [setid]) AS [GroupCount]
    FROM #Temp1
), DataSourceFilteringData AS
(
    SELECT *
          ,COUNT(*) OVER (PARTITION BY [setid]) AS [GroupCount]
    FROM #Temp2
)
SELECT A.[entryNo]
FROM DataSourceInialData A
INNER JOIN DataSourceFilteringData B
    ON A.[setid] = B.[setid]
    AND A.[measurid] = B.[measurid]
    AND A.[measurvalueid] = B.[measurvalueid]
    -- we are interested in groups which are passed completely by the filtering groups
    AND A.[GroupCount] = B.[GroupCount]
GROUP BY A.[entryNo]
-- aftering joining the rows, the filtered rows must match the filtering rows
HAVING COUNT(A.[setid]) = MAX(B.[GroupCount]);

算法很简单:

  1. 我们计算每个数据组存在多少行
  2. 我们计算每个过滤组存在多少行
  3. 我们加入了初始数据和过滤数据
  4. 在连接之后,我们计算初始数据中剩余的行数,以及计数是否等于给定组的过滤计数
  5. 结果是:

    enter image description here

    请注意,我正在检查每场比赛。例如,如果在您的示例数据中,entryNo = 1还有一行,则不会将其包含在结果中。要更改此行为,请对此行进行注释:

    -- we are interested in groups which are passed completely by the filtering groups
    AND A.[GroupCount] = B.[GroupCount]