我需要使用带有子查询的 select case 语句将以下过程 if else 语句更改为单个查询...
if((select COUNT(*) from pseb.dbo.meterattributedetails where meterid=@meterid)=0)
select @emf=EMF from pseb.dbo.METERMASTER where MeterID=@meterid
else if((select COUNT(*) from pseb.dbo.meterattributedetails where meterid=@meterid and dateadd(day,1,@fromdate)<DateTime)>0)
select top 1 @emf=oldvalue from pseb.dbo.meterattributedetails where MeterID=@meterid and dateadd(day,1,@fromdate)<datetime order by DateTime
else
select top 1 @emf=newvalue from pseb.dbo.meterattributedetails where meterid=@meterid and DateTime<@fromdate order by DateTime desc
米属性表结构如下:
AttributeID AttributeName Oldvalue newvalue DateTime meterid
1 EMF 2.00000 4.00000 2012-07-05 4756
1 EMF 4.00000 6.00000 2012-07-10 4756
1 EMF 6.00000 8.00000 2012-07-15 4756
1 EMF 8.00000 10.00000 2012-07-25 4756
在该表中 datetime 指的是 emf 更改日期,如果我的输入是“2012-07-17”,则意味着我必须获取该特定日期的新值,在 7 月 15 日至 25 日之间,emf 值为 8.00000。
我使用http://www.dpriver.com/pp/sqlformat.htm格式化了您的代码——迈克尔
IF( (SELECT Count(*)
FROM pseb.dbo.meterattributedetails
WHERE meterid = @meterid) = 0 )
SELECT @emf = emf
FROM pseb.dbo.metermaster
WHERE meterid = @meterid
ELSE IF( (SELECT Count(*)
FROM pseb.dbo.meterattributedetails
WHERE meterid = @meterid
AND Dateadd(day, 1, @fromdate) < datetime) > 0 )
SELECT TOP 1 @emf = oldvalue
FROM pseb.dbo.meterattributedetails
WHERE meterid = @meterid
AND Dateadd(day, 1, @fromdate) < datetime
ORDER BY datetime
ELSE
SELECT TOP 1 @emf = newvalue
FROM pseb.dbo.meterattributedetails
WHERE meterid = @meterid
AND datetime < @fromdate
ORDER BY datetime DESC