是否有满足两个TRUE条件的简单选择查询?

时间:2020-07-29 14:55:05

标签: sql-server tsql

我有一张有记录的桌子

FacilityID   StatusID    PaymentDuedate             EXPdate
0015617       1         2020-07-01 00:00:00.000    2020-06-30
0015617       2         2018-07-01 00:00:00.000    2020-06-30
0015617       5         2018-07-01 00:00:00.000    2020-06-30

为(1,2)中的记录状态和最新的付款到期日记录选择单个记录

在下面尝试过,但满足2个条件为TRUE,结果集为2条记录。有没有办法。我只需要作为SQL VIEW。应用程序不支持存储的PROC。

SELECT DISTINCT
       l.facility_id,
       [Report_Status_Id],
       MAX(payment_due_date) AS payment_due_date,
       CONVERT(date, DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, l.Expiration_Date), 0))) AS EXPdate
FROM a_license l
     JOIN (SELECT facility_id,
                  MAX(payment_due_date) AS payment_due_date,
                  [Report_Status_Id]
           FROM a_facility_annual_report
           GROUP BY facility_id,
                    [Report_Status_Id]) ar ON l.facility_id = ar.facility_id --and ar.payment_due_date=l.Expiration_Date
WHERE ar.[Report_Status_Id] IN (1, 2)
  AND l.facility_id IN ('0015617')
GROUP BY l.facility_id,
         [Report_Status_Id],
         Expiration_Date;

Output I need

    FacilityID    PaymentDuedate             EXPdate
     0015617    2020-07-01 00:00:00.000    2020-06-30

2 个答案:

答案 0 :(得分:1)

您可以将CROSS APPLY与TOP 1结合使用:

/folder/{folder}

答案 1 :(得分:0)

尝试使用case语句将状态(1,2)合并为一个状态1.如果以前在sql中没有使用过case语句,则可以解锁很多选项。

drop table t1
go
create table t1 (
Status int
)
go
insert into t1 values (1)
insert into t1 values (2)
go
select 
    case when status = 1 then 1 when status = 2 then 1 else 2 end, count(*)
from t1 
where 
    case when status = 1 then 1 when status = 2 then 1 else 2 end = 1
group by 
    case when status = 1 then 1 when status = 2 then 1 else 2 end