4

你能帮我建立一个 SQL 查询来从历史表中检索数据吗?

我是一个只有一周编码经验的新手。到目前为止,我一直在尝试简单的 SELECT 语句,但遇到了一个绊脚石。

我的足球俱乐部的数据库有三个表。第一个将球与球员联系起来:

BallDetail

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

第二个列出了球发生的事情:

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 |

第三个是历史变化表。球易手后,记录历史:

HistoryChanges

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

我正在尝试获取一张表格,该表格将列出球员 11 在球传给其他球员之前对所有球所做的所有传球和射门。像这样:

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

我开始这样:

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) ...

但是,如何确保 Ball 2 也被包括在内,尽管现在与另一名球员在一起?

4

2 回答 2

1
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)
于 2012-11-08T20:19:41.640 回答
1
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)
于 2012-11-09T15:18:50.953 回答