我有一个包含三列的表格:
PERSON
VISITOR
DATE
该表基本上是一个事务表。以下是真实的:
我需要的是
我试过了:
SELECT
ROW_NUMBER() OVER (PARTITION BY PERSON, VISITOR ORDER BY Date DESC) row_num,
PERSON,
VISITOR as VISITOR
FROM
`TABLE`
ORDER BY
PERSON
答案 0 :(得分:2)
也许这......不确定我完全理解问题。样本数据/预期结果会有所帮助。
你说你想要每个最大日期只有1个访问者,所以row_num为1将是最大日期的记录。而且由于我们按人分区,如果A人有3名访客则无关紧要。只会列出此人及其最近访客。
WITH cte as (
SELECT ROW_NUMBER() OVER (PARTITION BY PERSON ORDER BY Date DESC) row_num
, PERSON
, VISITOR as VISITOR
FROM `TABLE`)
SELECT *
FROM cte
WHERE row_Num = 1
我认为这可以通过交叉应用来完成,虽然我还不擅长使用它们......
SELECT A.Person, A.Visitor, A.Date
FROM table A
CROSS APPLY (SELECT TOP 1 *
FROM TABLE B
WHERE A.Person = B.Person
and A.Visitor = B.Visitor
and A.Date = B.Date
ORDER BY DATE DESC) C
本质上,内部查询针对外部查询的每条记录运行;因此,只返回最高记录,因此是最新的日期。
答案 1 :(得分:1)
select a.* from myTable as a inner join (
SELECT person, max(date) as maxDate from myTable group by person
) as b
on a.date = b.maxDate
and a.person = b.person;
答案 2 :(得分:0)
我在阅读和写英文方面很弱。 在我看来,答案可能是:
SELECT `PERSON`, `VISITOR`, MAX(`DATE`) AS `DATE`
FROM `TABLE`
GROUP BY `PERSON`, `VISITOR`;