我们有这张桌子,记录玩家的动作。我想知道人们在哪里购买他们的装备(Item
弓或剑)。该设备可以在商店或拍卖中购买(该地点可以在Action
栏中找到)。因此,当玩家购买商品时,我们需要找到Action
商店或拍卖(取决于购买商品之前最后一件商品)
**User Time Action Item**
1 12:00 Auction
2 12:01 Shop
3 12:04 Shop
4 12:09 Shop
4 12:15 Buy Bow
2 12:15 Auction
2 12:19 Auction
1 12:25 Chat
4 12:33 Auction
3 12:47 Chat
1 12:47 Buy Sword
2 12:47 Buy Bow
3 12:50 Buy Sword
4 12:52 Buy Bow
3 12:56 Buy Bow
结果应该是
**Time Item Place**
12:15 Bow Shop
12:47 Sword Auction
12:47 Bow Auction
12:50 Sword Shop
12:52 Bow Auction
12:56 Bow Shop
我想我有一个线索如何用mssql中的交叉应用来解决它,但是没有它可以解决它吗?我可能也必须在hive中使用查询。我会很感激任何答案。谢谢!
答案 0 :(得分:1)
你可能想要这样的东西(我猜你也可能喜欢那里的用户,嗯?)
更新的答案感谢蒂姆的建议
with p as -- pick purchases
(SELECT [user], [time] purchased, [item]
FROM actions
WHERE [action] = 'Buy'
), e as -- pick entrances where something can be bought
(SELECT [user], [time] entered, [action] place
FROM actions
WHERE [action] IN ('Auction', 'Shop')
), j as -- join purchases with all prior entrances
(SELECT p.[user], p.[purchased], p.[item],
e.[entered], e.[place]
FROM p
JOIN e on p.[user]=e.[user]
and p.[purchased]>=e.[entered]
), r as -- rank entrance closeness to purchase
(SELECT *, row_number() over( partition by [user],[purchased],[item]
order by [entered] desc ) as rnk
FROM j
) -- select only where entrance is the closest
SELECT [user],[purchased],[item],[place]
FROM r
WHERE rnk = 1
order by [user],[purchased],[item]
警告: TSQL不是我的母语; - )
答案 1 :(得分:0)
尝试:
select time, item, (
select top 1 Actions.action
from Actions
where Actions.[User] = buy.[user] and
Actions.action in ('shop', 'auction') and
Actions.time < buy.time
order by Actions.time desc
)
from Actions as buy
where action = 'buy'
感谢Tim Schmelter提供的sqlfiddle(很棒的工具,我不知道!!)