2011-12-15 54 views
0

我是一些在當前角色中接觸到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

我相信你要找的聲明是:EXCEPT。在兩條語句之間啪啪啪啪啪啪啪啪啪啪啪啪啪watch watch::::)))))))))))))))))))though) – 2011-12-15 05:34:55

回答

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

你可以離開了加入到你的異常表,並只接受空從參加比賽。

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