代码之家  ›  专栏  ›  技术社区  ›  David

在中使用Sql server

  •  0
  • David  · 技术社区  · 6 年前

    我有两个表Tbl\U Event(主键:-EventID)和Tbl\U items。

    tbl\u items表包含状态为0或1的同一EventID的多个项目。

    示例数据:

    Tbl_event:
    EventId  Name
    5        Test
    6        Seminar
    7        Meet
    
    tbl_items
    ItemId    EventId  status 
    1          5         0
    2          6         1
    2          6         0
    3          7         1
    3          7         1
    

    我只需要获取状态值为1的事件“Meet”。

    这就是我所尝试的:

    SELECT     *
    FROM       Tbl_items L
    INNER JOIN Tbl_Events E ON L.EventId = E.EventId 
    WHERE      L.Eventid NOT IN (SELECT Eventid FROM TBL_VMS_LENT_ITEMS WHERE Status = 0)
    
    4 回复  |  直到 6 年前
        1
  •  1
  •   Tim Biegeleisen    6 年前

    一种方法是使用子查询,该子查询聚合事件并检查所有状态是否为1:

    WITH cte AS (
        SELECT EventId
        FROM tbl_items
        GROUP BY EventId
        HAVING SUM(CASE WHEN status <> 1 THEN 1 ELSE 0 END) = 0
    )
    
    SELECT t1.*
    FROM Tbl_event t1
    INNER JOIN cte t2
        ON t1.EventId = t2.EventId;
    

    如果只需要事件ID,请使用 SELECT * FROM cte ,否则请使用我刚才给出的完整查询。如果以后需要,这种方法将推广到更复杂的逻辑。

        2
  •  1
  •   EzLo tumao kaixin    6 年前

    这将为您提供状态为1的所有项目的所有事件。

    SELECT
        E.EventID
    FROM
        Tbl_event AS E
        INNER JOIN tbl_items AS I ON E.EventID = I.EventID
    GROUP BY
        E.EventID
    HAVING
        MIN(I.status) = 1
    

    如果需要完整的事件记录:

    ;WITH EventsWithItemsStatus1 AS
    (
        SELECT
            E.EventID
        FROM
            Tbl_event AS E
            INNER JOIN tbl_items AS I ON E.EventID = I.EventID
        GROUP BY
            E.EventID
        HAVING
            MIN(I.status) = 1
    )
    SELECT
        E.*
    FROM
        Tbl_event AS E
        INNER JOIN EventsWithItemsStatus1 AS N ON E.EventID = N.EventID
    
        3
  •  0
  •   Yogesh Sharma    6 年前

    使用 group by 带有的子句 subquery

    select * from Tbl_event e
    inner join (
          select EventId  
          from tbl_items
          where status = 1 
          group by EventId  
          having count(*) > 1 
    ) i on i.EventId  = e.EventId  
    
        4
  •  0
  •   paparazzo    6 年前

    问题不是很清楚

    SELECT     min(L.ItemId), L.EventId
    FROM       Tbl_items L
    where      L.Status = 1 
    group by   L.EventId
    having count(*) > 1