如何在查询中执行此操作(提供示例)?

时间:2011-12-15 05:31:56

标签: sql sql-server tsql

我是一些新的SQL在我当前的角色中暴露给它。

如何编写以下查询以使其可以正常工作?

select *
from property.lease_period lp
where lp.lease_current_stop_date < getdate() and (lp.lease_status = 'Active' or lp.lease_status = 'Overholding')
and lp.period_id = 263      --- Period ID
and lp.building_id = 40000  --- Building ID
and not (SELECT *
            FROM property.lease_period lp
            inner join lease_deal.lease ld on lp.suite_id = ld.tenancy_reference
            where lp.lease_current_stop_date < getdate() and (lp.lease_status = 'Active' or lp.lease_status = 'Overholding')
            and lp.period_id = 263
            and lp.building_id = 40000)

基本上我想显示以下结果:

select *
from property.lease_period lp
where lp.lease_current_stop_date < getdate() and (lp.lease_status = 'Active' or lp.lease_status = 'Overholding')
and lp.period_id = 263      --- Period ID
and lp.building_id = 40000  --- Building ID

不包括匹配的结果:

SELECT *
FROM property.lease_period lp
inner join lease_deal.lease ld on lp.suite_id = ld.tenancy_reference
where lp.lease_current_stop_date < getdate() and (lp.lease_status = 'Active' or lp.lease_status = 'Overholding')
and lp.period_id = 263
and lp.building_id = 40000

对不起基本问题!此外,我们将非常感谢您更好地格式化我的SQL以外的任何其他提示!

修改

我相信这可能是我正在寻找的解决方案:

select
    *
from
    property.lease_period lp
where 
    lp.lease_current_stop_date < getdate() and (lp.lease_status = 'Active' or lp.lease_status = 'Overholding')
    and lp.period_id = 263      --- Period ID
    and lp.building_id = 40000  --- Building ID
    and not exists
    (
        select 1
        from lease_deal.lease
        where lp.suite_id = tenancy_reference
    )
order by period_id desc

绝对有兴趣听到更好的写作方法!

2 个答案:

答案 0 :(得分:1)

这可能是一种更简单的处理方式(以及我的个人格式偏好):

SELECT 
    *
FROM 
    property.lease_period lp
WHERE
    lp.lease_current_stop_date < GETDATE() 
    AND
    (lp.lease_status = 'Active' or lp.lease_status = 'Overholding')
    AND 
    lp.period_id = 263      --- Period ID
    AND
    lp.building_id = 40000  --- Building ID
    AND
    lp.suite_id NOT IN (SELECT tenancy_reference FROM lease_deal.lease)

答案 1 :(得分:1)

您可以将连接保留到异常表中,只接受来自该连接的空匹配。

select lp.*
from property.lease_period lp
left join lease_deal.lease ld on lp.suite_id = ld.tenancy_reference
where lp.lease_current_stop_date < getdate()
and (lp.lease_status = 'Active' or lp.lease_status = 'Overholding')
and lp.period_id = 263      --- Period ID
and lp.building_id = 40000  --- Building ID
and ld.tenancy_reference is null