【问题标题】:SQL Count condition in main Query主查询中的 SQL 计数条件
【发布时间】:2020-07-26 23:54:02
【问题描述】:

我想为is_initial_event 列选择那些值:值可以是 0 或 1。我只想要那些只有 1 的人。不是说他们同时有 1 和 0。@ 有多个详细信息行987654322@.

select ac.Full_name, pe.program_start_date, pe.program_end_date, tp.approved_by_Description as 
    Approved, ev.is_initial_event, tp.staff from all_clients_view ac  
inner join program_enrollment_expanded_view pe
    on ac.people_id = pe.people_id
inner join  service_plan_goals_objectives_methods_view tp
    on ac.people_id = tp.people_id
inner join service_plan_event_view ev
    on ac.people_id = ev.people_id
where pe.program_name = 'CFTSS' and tp.Approved_by_description is null 

这里我尝试添加计数,我想计算的是如果 people_id 对于 ev.Is_initial_event = 1 有 > 0 并且在 ev.IS_initial_event = 0 时也有 >,那么我不想要那个 people_id只有当它只有 ev.is_initial_event = 1 而不是两者都有记录时。

【问题讨论】:

  • 样本数据和期望的结果会很有帮助。

标签: sql sql-server where-clause window-functions


【解决方案1】:

您在寻找窗口函数吗?

select *
from (
    select 
        ac.Full_name, 
        pe.program_start_date, 
        pe.program_end_date, 
        tp.approved_by_Description as Approved, 
        ev.is_initial_event, 
        tp.staff,
        min(ev.is_initial_event) over(partition by ac.people_id) min_initial_event
    from all_clients_view ac  
    inner join program_enrollment_expanded_view pe
        on ac.people_id = pe.people_id
    inner join service_plan_goals_objectives_methods_view tp
        on ac.people_id = tp.people_id
    inner join service_plan_event_view ev
        on ac.people_id = ev.people_id
    where 
        pe.program_name = 'CFTSS' 
        and tp.Approved_by_description is null
) t
where min_initial_event = 1

这将返回具有相同people_id 的所有行将initial_event 设置为1 的行(请注意,这假定此列仅包含0s 和1s,如您的问题中所述)。

【讨论】:

  • 谢谢 GMB-min_initial_event 是什么?应该是 min(is_initial_event)
  • @PasPalter:这是在子查询中定义的窗口 min() 的别名。
  • HI 它给出一个错误 - 消息 8117,级别 16,状态 1,第 10 行操作数数据类型位对于 min 运算符无效。
  • @PasPalter:好的,现在我们知道您使用的是 SQL Server,并且此列是“BIT”数据类型。如果是这样,只需将min(ev.is_initial_event) 更改为min(ev.is_initial_event + 0)
  • 刚刚有一个问题 - 我们是否有一种情况,即我们也希望为 Null 的行,有些仅为 null 而不是 1 或 0。
猜你喜欢
  • 2014-04-09
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
相关资源
最近更新 更多