【发布时间】:2017-06-28 22:14:06
【问题描述】:
我的表结构如下:
| TxnID | CardID | WhereName | FirstName | LastName | DateTimeOfxTxn | .....|
----------------------------------------------------------------------------------------
| 1 | 1 | location1 | test | employee1 | 2017-06-28 00:01:00 | |
| 2 | 1 | location2 | test | employee1 | 2017-06-28 00:02:00 | |
| 3 | 2 | location1 | test | employee2 | 2017-06-28 00:03:00 | |
| 4 | 1 | location3 | test | employee1 | 2017-06-28 00:03:30 | |
| 5 | 1 | location1 | test | employee1 | 2017-06-28 00:04:00 | |
| 6 | 2 | location2 | test | employee2 | 2017-06-28 00:05:00 | |
现在,我有以下 SQL 查询:
WITH t1 AS (
SELECT
CardID,
MIN(DateTimeOfTxn) AS mindate,
MAX(DateTimeOfTxn) AS maxdate
FROM ActivityDataView
where convert(datetime, floor(convert(float, DateTimeOfTxn))) = '06/28/2017'
GROUP BY CardID
)
SELECT
t2.CardID,
t2.WhereName as Location,
t2.FirstName + ' ' + t2.LastName as Name,
t1.mindate,
t1.maxdate
FROM ActivityDataView AS t2
JOIN t1
ON (t2.CardID = t1.CardID AND t2.DateTimeOfTxn = t1.mindate)
OR (t2.CardID = t1.CardID AND t2.DateTimeOfTxn = t1.maxdate)
order by CardID
该查询将选择与 Min(date) 相关的行,然后还选择 Max(date) 的行。
返回我:
| CardID | Location | Name | MinDate | MaxDate
------------------------------------------------------------------------------------------
| 1 | location1 | test employee1 | 2017-06-28 00:01:00 | 2017-06-28 00:04:00 |
| 1 | location1 | test employee1 | 2017-06-28 00:01:00 | 2017-06-28 00:04:00 |
| 2 | location1 | test employee2 | 2017-06-28 00:03:00 | 2017-06-28 00:05:00 |
| 2 | location2 | test employee2 | 2017-06-28 00:03:00 | 2017-06-28 00:05:00 |
我希望能够得到这个:
| CardID | Name | MinDate | MinLocation | MaxDate | MaxLocation |
--------------------------------------------------------------------------------------------------------
| 1 | test employee1 | 2017-06-28 00:01:00 | location1 | 2017-06-28 00:04:00 | location 1 |
| 2 | test employee2 | 2017-06-28 00:03:00 | location1 | 2017-06-28 00:05:00 | location 2 |
我对 SQL 查询很陌生,所以我不确定如何实现我想要的。任何帮助都会很棒。
【问题讨论】:
标签: sql sql-server sql-server-2008-r2