选择记录基于sql server中的组

时间:2015-12-24 19:10:46

标签: sql-server

我有一个场景,其中有两个表,一个是MAIN,第二个是Child。 可能有4种状态类型 1 =未开始 2 =开始 3 =跑步 4 =已停止

我在每个主表行的子项中都有随机记录,我只需要找出Child表中仅使用状态(1,4)的记录数。

下面我正在附上剧本。

   CREATE TABLE #Main
   (
     ID INT ,
     CreateDateTime DATETIME ,
     LLevel INT
)
 CREATE TABLE #Child
   (
     ID INT ,
     MainID INT ,
     STATUS INT
   )
   -- Status(1= NotStarted, 2= Started ,3 = Ruunning ,4 = Stopped)

    INSERT  INTO #Main
    SELECT  1 ,
            '2015-12-24 18:48:41' ,
            1
    UNION ALL
    SELECT  2 ,
            '2015-12-24 18:49:59' ,
            3
    UNION ALL
    SELECT  3 ,
            '2015-12-24 18:51:01' ,
            1
    UNION ALL
    SELECT  4 ,
            '2015-12-24 18:53:11' ,
            4
    UNION ALL
    SELECT  5 ,
            '2015-12-24 18:57:11' ,
            2



    INSERT  INTO #Child
    SELECT  1 ,
            1 ,
            1  --  MIAN ID = 1
    UNION ALL
    SELECT  2 ,
            1 ,
            2
    UNION ALL
    SELECT  3 ,
            1 ,
            3
    UNION ALL
    SELECT  4 ,
            2 ,
            1  --  MIAN ID = 2
    UNION ALL
    SELECT  5 ,
            2 ,
            4
    UNION ALL
    SELECT  6 ,
            3 ,
            1  --  MIAN ID = 3
    UNION ALL
    SELECT  7 ,
            3 ,
            2
    UNION ALL
    SELECT  8 ,
            3 ,
            3
    UNION ALL
    SELECT  9 ,
            4 ,
            1  --  MIAN ID = 4
    UNION ALL
    SELECT  10 ,
            4 ,
            2
    UNION ALL
    SELECT  11 ,
            4 ,
            3
    UNION ALL
    SELECT  12 ,
            5 ,
            1  --  MIAN ID = 2
    UNION ALL
    SELECT  13 ,
            5 ,
            4

SELECT  *
FROM    #Main
SELECT  *
FROM    #Child
ORDER BY MainID ASC

DROP TABLE #Main
DROP TABLE #Child

我附上了一张图片,我需要的这些记录,意味着数量应该是两个。 enter image description here

2 个答案:

答案 0 :(得分:0)

这可能不是最快的方法,但优化器会让它关闭。此外,很明显,这是正确的,并了解它如何使用CTE

WITH haveone as
(
   SELECT DISTINCT MainID as ID 
   FROM #Child 
   WHERE STATUS = 1
), havefour as
(
   SELECT DISTINCT MainID as ID 
   FROM #Child 
   WHERE STATUS = 4
), haveboth as
(
  SELECT haveone.ID 
  FROM haveone
  JOIN havefour ON haveone.ID = havefour.ID
), haveother as
(
  SELECT DISTINCT MainID as ID
  FROM #Child
  WHERE STATUS NOT IN (1,4)
)
SELECT ID
FROM haveboth
WHERE ID NOT IN (SELECT ID FROM haveother)

答案 1 :(得分:0)

我已经弄清楚并以这种方式产生了结果。

SELECT  count(m.id) FROM #main m INNER JOIN #child c on m.id = c.mainid and c.status in (1,4) 
and c.mainid not in (select mainid from #child where status in (2,3))   group   by m.id
having count(m.id) = 2