0

如何在不使用子查询的情况下获取聚合函数的记录详细信息?

我有一个数据集如下:

CREATE TABLE SOMEDATA(
id int, 
low int, 
op int,
yc int,
tc int,
volume int,
Atimestamp time)

INSERT INTO SOMEDATA VALUES(5631,       5500,       5600,   5680,           5680,       300527,     '13:16:12.462')
INSERT INTO SOMEDATA VALUES(5631,       5500,       5600,   5680,           5680,       301720,     '13:16:13.304')
INSERT INTO SOMEDATA VALUES(5631,       5500,       5600,   5680,           5680,       302041,     '13:16:13.306')
INSERT INTO SOMEDATA VALUES(5631,       5500,       5600,   5680,           5680,       302410,     '13:16:13.682')
INSERT INTO SOMEDATA VALUES(5631,       5500,       5600,   5680,           5680,       302548,     '13:16:15.818')
INSERT INTO SOMEDATA VALUES(5632,       5500,       5600,   5680,           5680,       302548,     '13:16:15.818')

我通过以下方式查询:

SELECT * FROM SOMEDATA 
INNER JOIN (select max(Atimestamp) as tm,id FROM SOMEDATA group by id) t 
on t.tm = SOMEDATA.Atimestamp AND SOMEDATA.id = t.id  

不过,这似乎是一种不好的方法(例如,据我了解,此查询将表锁定了两次)-是否有更好的方法来做到这一点(也许使用 HAVING )?

4

3 回答 3

1

您应该能够为此使用 RANK() 函数。就像是:

SELECT id, low, op, yc, tc, volume, Atimestamp
FROM
(
  SELECT 
    id, 
    low, 
    op,
    yc,
    tc,
    volume, 
    Atimestamp,
    RANK() OVER (PARTITION BY id ORDER BY Atimestamp DESC) AS rank
FROM somedata
) a
WHERE a.rnk = 1
于 2013-07-08T11:45:06.623 回答
1

请试试:

SELECT * FROM(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY Atimestamp DESC) RNum
    From SOMEDATA
)x
WHERE RNum=1

或者

;WITH x AS(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY Atimestamp DESC) RNum
    From SOMEDATA
)
SELECT * FROM x
WHERE RNum=1
于 2013-07-08T11:45:12.423 回答
0
  SELECT id, low, op, yc, tc, max (Atimestamp)
  FROM SOMEDATA 
  GROUP BY id, low, op, yc, tc   

对于聚合列,您需要使用 GROUP BY

于 2013-07-08T11:47:01.207 回答