如何使用没有子查询的聚合函数获取行的详细信息?

时间:2013-07-08 11:37:36

标签: sql sql-server

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

我的数据集如下:

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

请尝试:

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

OR

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

答案 2 :(得分:0)

  SELECT id, low, op, yc, tc, max (Atimestamp)
  FROM SOMEDATA 
  GROUP BY id, low, op, yc, tc   

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