繁体   English   中英

SQL Server 2008-在相关查询上需要帮助

[英]SQL Server 2008 - need help on a antithetical query

我想查找给定交易日的抄表。 在某些情况下,不会有任何抄表,并且希望查看前一天的抄表。

示例数据集如下。 我正在使用SQL Server 2008

declare   @meter table (UnitID int, reading_Date date,reading int)
declare @Transactions table (Transactions_ID int,UnitID int,Transactions_date date)


insert into  @meter (UnitID,reading_Date,reading ) values 
(1,'1/1/2014',1000),
(1,'2/1/2014',1010),
(1,'3/1/2014',1020),
(2,'1/1/2014',1001),
(3,'1/1/2014',1002);

insert into  @Transactions(Transactions_ID,UnitID,Transactions_date) values
(1,1,'1/1/2014'),
(2,1,'2/1/2014'),
(3,1,'3/1/2014'),
(4,1,'4/1/2014'),
(5,2,'1/1/2014'),
(6,2,'3/1/2014'),
(7,3,'4/1/2014');

select * from @meter;
select * from @Transactions;

我希望得到以下输出

Transactions
Transactions_ID     UnitID  Transactions_date   reading 
1                   1       1/1/2014            1000
2                   1       2/1/2014            1010
3                   1       3/1/2014            1020
4                   1       4/1/2014            1020
5                   2       1/1/2014            1001
6                   2       3/1/2014            1001
7                   3       4/1/2014            1002

您的SQL查询将获得所需的结果,如下所示:

SELECT Transactions_ID, T.UnitID, Transactions_date
, (CASE WHEN ISNULL(M.reading,'') = '' THEN 
         (
             SELECT MAX(Reading) FROM @meter AS A 
             JOIN @Transactions AS B ON A.UnitID=B.UnitID AND A.UnitID=T.UnitID 
         )
   ELSE M.reading END) AS Reading
FROM @meter AS M
RIGHT OUTER JOIN @Transactions AS T ON T.UnitID=M.UnitID 
AND T.Transactions_date=M.reading_Date

我可以想到两种解决方法-都不是理想的方法。

第一种(略好一点)的方法是创建一个SQL函数,该函数将Transactions_date作为参数并返回Max(Reading_date)的读数,其中reading_date <= transaction_date。 然后,您可以在针对Transactions表的select语句中使用此功能。

另一种方法是使用游标遍历事务表,并使用与上述相同的逻辑,在该方法中,您返回Max(Reading_date)的读数,其中reading_date <= transaction_date。

请尝试以下查询:

请在SQLFiddle中找到相同的结果

select a.Transactions_ID, a.UnitID, a.Transactions_date,
case when b.reading IS NULL then c.rd else b.reading end as reading
from
Transactions a 
left outer join
meter b 
on a.UnitID = b.UnitID
and a.Transactions_date = b.reading_Date
inner join 
(
select UnitID,max(reading) as rd
from meter
group by UnitID
) as C
on a.UnitID = c.UnitID 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM