我的SQL数据库中有以下视图,它从事务表和客户表中选择数据:
+-------+-----------+---------------------+--------+
| RowNo | Name | Date | Amount |
+-------+-----------+---------------------+--------+
| 1 | Customer1 | 2018-11-10 01:00:00 | 55.49 |
| 2 | Customer2 | 2018-11-10 02:00:00 | 58.15 |
| 3 | Customer3 | 2018-11-10 03:00:00 | 79.15 |
| 4 | Customer1 | 2018-11-11 04:00:00 | 41.89 |
| 5 | Customer2 | 2018-11-11 05:00:00 | 5.15 |
| 6 | Customer3 | 2018-11-11 06:00:00 | 35.17 |
| 7 | Customer1 | 2018-11-12 07:00:00 | 43.78 |
| 8 | Customer1 | 2018-11-12 08:00:00 | 93.78 |
| 9 | Customer2 | 2018-11-12 09:00:00 | 80.74 |
+-------+-----------+---------------------+--------+我需要一个SQL查询,该查询将返回给定一天的所有客户事务(非常容易),但是如果客户在给定的一天没有事务,则查询必须返回客户的最新事务。
编辑:
意见如下:
Create view vwReport as
Select c.Name, t.Date, t.Amount
from Transaction t
inner join Customer c on c.Id = t.CustomerId然后,为了获得数据,我只需从视图中选择:
Select * from
vwReport r
where r.Date between '2018-11-10 00:00:00' and '2018-11-11 00:00:00'因此,为了澄清,我需要一个查询,它返回一天的所有客户事务,并包含在结果集中,这是任何在当天没有事务的客户的最后一个事务。因此,在上表中,运行2018-11-12查询时,应该返回第7、8和9行,以及在12号没有事务处理的Customer3的第6行。
发布于 2018-11-19 14:14:23
以您现有的查询为例,为每个没有该范围内的事务的人提供“最近的事务查询”( UNION ALL it )。
with found as
(
select c.Id, c.Name, t.Date, t.Amount
from Transaction t
inner join Customer c on c.Id = t.CustomerId
where Date between '2018-11-10 00:00:00' and '2018-11-11 00:00:00'
)
with unfound as
(
select c.Id, c.Name, t.Date, t.Amount, RANK() OVER (PARTITION BY Name ORDER BY CAST(Date AS DATE) DESC) AS row
from Transaction t
inner join Customer c on c.Id = t.CustomerId
WHERE Date < '2018-11-10 00:00:00'
)
select Name, Date, Amount
from found
union all
select Name, Date, Amount
from unfound
where Id not in ( select Id from found ) and row = 1发布于 2018-11-19 13:05:42
您对选择多个带有领带的行感兴趣,您可以使用RANK()函数查找按日期降序排列的所有行:
SELECT * FROM (
SELECT *, RANK() OVER (PARTITION BY Name ORDER BY CAST(Date AS DATE) DESC) AS rn
FROM txntbl
WHERE CAST(Date AS DATE) <= '2018-11-12'
) AS x
WHERE rn = 1发布于 2018-11-19 12:53:00
您可以使用关联子查询:
select t.*
from transactions t
where t.date = (select max(t2.date)
from transactions t2
where t2.name = t.name and
t2.date <= @date
);注意:这只返回在有关日期或之前有交易的客户。
https://stackoverflow.com/questions/53375050
复制相似问题