2016-05-21 5 views
1

同じAgencyMaster IDに対して、異なるeffectiveStart dateとeffectiveEnd dateを持つ複数のエントリと、 effectiveEndおよびeffectiveStartをnullとして返します。どのように日付が指定されたレコードが存在する場合はnull日付レコードを避ける他にnull日付を持つレコードを取得する必要があります

私は、エントリを持っていない日付を与えている場合は、そのeffectiveStartとeffectiveEndの日付でnullに対応するレコードとしてeffectiveEndとeffectiveStartでレコードを返す必要がありますが、ここで私の問題は、特定の日付の日付とレコード、合計2レコードです。これを回避する方法。テーブル画面を添付

select AgencyBillingSettingsMaster.AgencyBillingSettingMasterID, * 
from AgencyBillingSettingsMaster 
where (AgencyBillingSettingsMaster.effectivePeriodStart is not null and 
     AgencyBillingSettingsMaster.effectivePeriodEnd is not null and 
     (convert(datetime,@EffectivePeriod)>=effectivePeriodStart and 
     convert(datetime,@EffectivePeriod)<effectivePeriodEnd) 
     or (AgencyBillingSettingsMaster.effectivePeriodStart is null and 
      AgencyBillingSettingsMaster.effectivePeriodEnd is null)) 

は、それは条件付きの組合を得るためにUNIONとの組み合わせで機能FOUND_ROWS()を使用するMySQLの中で可能である

enter image description here

+0

は、なぜあなたはヌル開始日を持っているでしょうか? – Strawberry

答えて

0

を撃った:

SELECT .... FROM ... WHERE your_condition_for_existing_dates_here 
UNION ALL 
SELECT .... FROM ... WHERE FOUND_ROWS() = 0 AND your_condition_for_null_dates_here 

あなたクエリは次のようになります:

select AgencyBillingSettingsMaster.AgencyBillingSettingMasterID, * 
from AgencyBillingSettingsMaster 
where (AgencyBillingSettingsMaster.effectivePeriodStart is not null and 
     AgencyBillingSettingsMaster.effectivePeriodEnd is not null and 
     (convert(datetime,@EffectivePeriod)>=effectivePeriodStart and 
     convert(datetime,@EffectivePeriod)<effectivePeriodEnd) 
union all 
select AgencyBillingSettingsMaster.AgencyBillingSettingMasterID, * 
from AgencyBillingSettingsMaster 
where found_rows() = 0 
     and (AgencyBillingSettingsMaster.effectivePeriodStart is null and 
      AgencyBillingSettingsMaster.effectivePeriodEnd is null)) 
1

あなたは閉じ括弧を間違って配置したと思います。各条件は別々にする必要がありますが、現在のコードではすべて単一条件になります。

コードはあなたの問題を解決します:

select AgencyBillingSettingsMaster.AgencyBillingSettingMasterID, * 
from AgencyBillingSettingsMaster 
where (AgencyBillingSettingsMaster.effectivePeriodStart is not null and 
     AgencyBillingSettingsMaster.effectivePeriodEnd is not null and 
     (convert(datetime,@EffectivePeriod)>=effectivePeriodStart and 
     convert(datetime,@EffectivePeriod)<effectivePeriodEnd)) -- here the first condition need to close 
     or -- the second condition should have another block 
      (AgencyBillingSettingsMaster.effectivePeriodStart is null and 
      AgencyBillingSettingsMaster.effectivePeriodEnd is null) 
関連する問題