将查询结果限制为 2 个 JOINED 表之一的行数

Limiting Query Result to number of rows of ONE of 2 JOINED tables

我打算将查询结果限制为第 Table 部分中的行(126 行) 但是我的查询一直为事件 Table(QUERY 1) 或错误消息 (QUERY 2) 提供 725 行 如何编写此 JOIN 查询并将输出限制为第 Table?

部分中的行数

查询 1

SELECT      
CASE WHEN e.EventActive='y' 
THEN 'Active' ELSE 'Inactive' END AS EventActive, 
COUNT(*) AS 'Total'
FROM       ADF_Section s
INNER JOIN ADF_Event e
ON          s.SectionID = e.SectionID
GROUP BY
CASE WHEN e.EventActive='y' 
THEN 'Active' ELSE 'Inactive' END

查询 2

SELECT      s.*, e.EventActive
FROM        ADF_Section s
INNER JOIN ADF_Event e
ON         s.SectionID = e.SectionID
HAVING     s.CourseID<= 1037
GROUP BY   s.*, e.EventActive

以下是计算每个部分的 Active/Inactive 状态的方法:

select s.SectionID, 
  case 
    -- if all Events in the series are 'y, 
    -- Section is considered 'Active':
    when min(e.EventActive) = 'y' and max(e.EventActive) = 'y' then 'Active'

    -- there are both active and inactive Events,
    -- display NULL (according to your comment):
    when min(e.EventActive) < max(e.EventActive) then null

    -- in case none of the above scenarios are met, 
    -- it means that all Events are inactive, so we 
    -- consider Section to be inactive as well:
    else 'Inactive'
  end as EventActive
from ADF_Section s
join ADF_Event e
  on s.SectionID = e.SectionID
group by s.SectionID;

我在这里用一些随机数据创建了一个测试场景:http://www.sqlfiddle.com/#!3/aa0a3/1

如果您需要根据 CourseID 筛选 Section,请将此筛选器添加到 WHERE 子句中,并确保将筛选的字段包含在 GROUP BY 中还有:

select s.SectionID, 
  case 
    when min(e.EventActive) = 'y' and max(e.EventActive) = 'y' then 'Active'
    when min(e.EventActive) < max(e.EventActive) then null
    else 'Inactive'
  end as EventActive
from ADF_Section s
join ADF_Event e
  on s.SectionID = e.SectionID
where s.CourseId <= 1037
group by s.SectionID, s.CourseID;

我想你想要exists:

SELECT s.*,
       (CASE WHEN EXISTS (SELECT 1
                          FROM ADF_EVENT e
                          WHERE s.SectionID = e.SectionID AND e.EventActive = 'y'
                         )
             THEN 'y' ELSE 'n'
        END) as EventActive
FROM  ADF_Section s
WHERE s.CourseID <= 1037;

如果您有大量数据,这将受益于索引:ADF_Section(CourseId, SectionId)ADF_Event(SectionId, EventActive)

注意:这假定当与该部分关联的任何事件处于活动状态时,事件处于活动状态。如果逻辑确实是 all 需要激活并且至少有一个,则以下逻辑应该有效:

       (CASE WHEN EXISTS (SELECT 1
                          FROM ADF_EVENT e
                          WHERE s.SectionID = e.SectionID
                          GROUP BY e.SectionId
                          HAVING MIN(EventActive) = MAX(EventActive) AND MIN(EventActive) = 'y'
                         )
             THEN 'y' ELSE 'n'