我有两个简单的表定义为:
CREATE TABLE [dbo].[shop](
[id] [uniqueidentifier] NOT NULL,
[name] [ntext] NOT NULL,
[brand] [ntext] NULL
)
CREATE TABLE [dbo].[shop_history](
[id] [int] NOT NULL,
[shopid] [uniqueidentifier] NOT NULL, (references shop.id)
[totalstockval] [int] NOT NULL,
[date] [datetime2](0) NOT NULL
)
使用数据:
**dbo.shop**
id | name | brand
--------------------------
1 | Bow Rd | Tesco
2 | Wren Rd | Tesco
3 | Skye Rd | Safeway
**dbo.shop_history**
id | shopid | totalstockval | date
----------------------------------------------
997 | 1 | 19923031 | 2017-02-01 08:00
998 | 1 | 19323322 | 2017-02-01 08:30
999 | 1 | 19283873 | 2017-02-01 09:45
1000 | 2 | 14949321 | 2017-02-01 07:00
1001 | 2 | 12312312 | 2017-02-01 09:30
1002 | 3 | 12232344 | 2017-01-31 23:45
1003 | 3 | 12999222 | 2017-02-01 09:45
我有一整年的类似数据。我想查询数据,以便在每天09:00之前找到最新的股票价值,即使这是在前一天发生的。
我想要实现的结果集如下:
shop.id | name | brand | totalstockval | date
---------------------------------------------------------------
1 | Bow Rd | Tesco | 19323322 | 2017-02-01 08:30
2 | Wren Rd | Tesco | 14949321 | 2017-02-01 07:00
3 | Skye Rd | Safeway | 12232344 | 2017-01-31 23:45
一年中的每一天重复。如果特定日期没有值行,请使用最新的可用值。
我有一种感觉,我需要一个包含我想要价格的每个日期(或日期时间)的计数表,但我不确定查询。如何实现类似于上面示例的结果集?
答案 0 :(得分:0)
可能是您需要使用subselect进行最大日期< 9
select t.shopid, b.name, b.brand, t.max_date, a.totalstockvale
from shop_history a
inner join (
select shopid, max(date) max_date
from shop_history a
where time(date) < '09:00'
group by a.shopid ) t on a.shopid = t.shopid and a.date = t.date
inner join shop on a.shopid = b.shopid
答案 1 :(得分:0)
这是一个棘手的问题。您希望每天上午9:00结束的每家商店都有最新的shop_history
记录。一种方法是减去9小时,并根据结果日期进行计算:
select sh.*
from (select sh.*,
row_number() over (partition by shopid,
cast(dateadd(hour, -9, date) as date)
order by date desc
) as seqnum
from shop_history sh
) sh
where seqnum = 1