3

我们有这张表,其中记录了玩家的动作。我想知道人们在哪里购买他们的装备(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 中使用交叉应用来解决它,但是没有它是否可以解决它?我可能还必须在配置单元中使用查询。我将不胜感激。谢谢!

4

2 回答 2

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 不是我的母语;-)

于 2013-03-26T23:19:05.573 回答
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 测试(很棒的工具,我不知道!!)

于 2013-03-26T23:33:03.963 回答