我在处理复杂的(对我来说无论如何)查询时遇到了困难。
我正在查询的表有 3 个列,ClientID(int Not Null)、ProductID(int Not Null)和 ExpiryDate(smalldatetime 可为空)
给定两个客户 ID 的 Master 和 Consolidated,我需要执行以下业务逻辑来返回单个数据集:
为两个 clientID 的到期日期都不为空的产品选择到期日期较长的 ClientID
为一个有效期为空而另一个不为空的产品选择有效期为空的 ClientID
为两个到期日期都为空或两个到期日期相同的产品选择 MasterID。
我尝试了以下方法,但卡住了......
Create Table #ProductSub (ClientID int NOT NULL,
ProductID int NOT NULL,
ExpiryDate smalldatetime)
/* In real life there is a Clustered Primary Key On ClientID and ProductID
Load Up Some Test Data */
Insert into #ProductSub Values (1, 100, null)
Insert into #ProductSub Values (2, 100, null)
Insert into #ProductSub Values (1, 101, null)
Insert into #ProductSub Values (2, 102, null)
Insert into #ProductSub Values (1, 200, null)
Insert into #ProductSub Values (2, 200, '2009-01-01')
Insert into #ProductSub Values (1, 300, '2009-01-01')
Insert into #ProductSub Values (2, 300, null)
Insert into #ProductSub Values (1, 400, '2009-01-01')
Insert into #ProductSub Values (2, 400, '2008-01-01')
Insert into #ProductSub Values (1, 500, '2008-01-01')
Insert into #ProductSub Values (2, 500, '2009-01-01')
Insert into #ProductSub Values (1, 600, '2009-01-01')
Insert into #ProductSub Values (2, 600, '2009-01-01')
--Select * from #ProductSub
Declare @MasterClient int,
@ConsolClient int
Select @MasterClient = 1, @ConsolClient = 2
Select * from #ProductSub t1
/* Use Master Client ID When Expiry Date is Null) */
Where (ClientID = @MasterClient and ExpiryDate is null)
/* Use Consol ClientID if Expiry Date is null nut Expiry Date for Master Client ID is not */
OR (ClientID = @ConsolClient and ExpiryDate is null and ProductID not in (
Select ProductID from #ProductSub t2
Where (ClientID = @MasterClient and ExpiryDate is null))
)
OR -- OH NO my head exploded
/* OR EXISTS (Select 1
from #ProductSub t3
)*/
Drop Table #ProductSub
/********** Expected Output ************************
ClientID ProductID ExpiryDate
1 100 NULL
1 101 NULL
2 102 NULL
1 200 NULL
2 300 NULL
1 400 2009-01-01 00:00:00
2 500 2009-01-01 00:00:00
1 600 2009-01-01 00:00:00
非常感谢任何和所有帮助
编辑:虽然听起来像,但这不是家庭作业,而是一个现实生活中的问题,我希望找到一个现实生活中的解决方案,我可以自己做,但我所有的解决方案都在通往临时表的道路上。我应该指出生产环境是SQLServer 7!