简体   繁体   中英

SQL Server: how do I get data from a history table?

Can you please help me build an SQL query to retrieve data from a history table?

I'm a newbie with only a one-week coding experience. I've been trying simple SELECT statements so far but have hit a stumbling block.

My football club's database has three tables. The first one links balls to players:

BallDetail

| BallID | PlayerID | TeamID |
|-------------------|--------|
|      1 |       11 |     21 |
|      2 |       12 |     22 |

The second one lists things that happen to the balls:

BallEventHistory

| BallID | Event |  EventDate |
|--------|------ |------------|
|      1 |  Pass | 2012-01-01 |
|      1 | Shoot | 2012-02-01 |
|      1 |  Miss | 2012-03-01 |
|      2 |  Pass | 2012-01-01 |
|      2 | Shoot | 2012-02-01 |

And the third one is a history change table. After a ball changes hands, history is recorded:

HistoryChanges

| BallID | ColumnName | ValueOld | ValueNew |
|--------|------------|----------|----------|
|      2 |   PlayerID |       11 |       12 |
|      2 |     TeamID |       21 |       22 |

I'm trying to obtain a table that would list all passes and shoots Player 11 had done to all balls before the balls went to other players. Like this:

| PlayerID | BallID | Event | Month |
|----------|--------|-------|-------|
|       11 |      1 |  Pass |   Jan |
|       11 |      1 | Shoot |   Feb |
|       11 |      2 |  Pass |   Jan |

I begin so:

SELECT PlayerID, BallID, Event, DateName(month, EventDate)
FROM BallDetail bd INNER JOIN BallEventHistory beh ON bd.BallID = beh.BallID
WHERE PlayerID = 11 AND Event IN (Pass, Shoot) ...

But how to make sure that Ball 2 also gets included despite being with another player now?

Select PlayerID,BallID,Event,datename(month,EventDate) as Month,Count(*) as cnt from
(
Select 
Coalesce(
(Select ValueNew from #HistoryChanges where ChangeDate=(Select max(ChangeDate) from #HistoryChanges h2 where h2.BallID=h.BallID and ColumnName='PlayerID' and ChangeDate<=EventDate) and  BallID=h.BallID and ColumnName='PlayerID')
,(Select PlayerID from #BallDetail where BallID=h.BallID)
) as PlayerID,
h.BallID,h.Event,EventDate
from #BallEventHistory h
) a
Group by PlayerID, BallID, Event,datename(month,EventDate)
SELECT d.PlayerID, d.BallID, h.Event, DATENAME(mm, h.EventDate) AS Month
FROM BallDetail d JOIN BallEventHistory h ON d.BallID = h.BallID 
WHERE h.Event IN ('Pass', 'Shoot') AND d.PlayerID = 11
  OR EXISTS (SELECT 1
             FROM dbo.HistoryChanges c
             WHERE c.ValueOld = 11 AND c.ValueNew = d.PlayerID AND c.ColumnName = 'PlayerID' and c.ChangeDate = h.EventDate)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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