帮助SQL查询

时间:2010-03-11 23:12:01

标签: sql

我该怎么做?我有3行像这样:

ID         THREAD         POST
1            1              Hello World
2            2              Hello galaxy
3            2              Hello people

我只需要使用最低ID为每个线程返回ID,线程和发布一次。

类似的东西:

SELECT * FROM table WHERE THREAD DISTINT AND ID = MIN(ID)

编辑:为了更清楚在这个例子中它应该只返回1和2的行,因为3不是线程为2的最低ID

编辑2:它需要返回第1行和第2行。

3 个答案:

答案 0 :(得分:3)

在SQL Server 2005及更高版本中:

SELECT t.Id, t.Thread, t.Post
FROM 
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY Thread ORDER BY Id) as RowNumInThread
FROM table
) t
WHERE t.RowNumInThread = 1
;

SELECT t.*
FROM 
(
  SELECT Min(Id) as MinId
  FROM table
  GROUP BY Thread
) tmin
JOIN
table t   ON t.Id = tmin.Id
;

答案 1 :(得分:2)

select id, thread, post
from t
inner join (
select min(id)
from t
group by thread) subq on t.id = subq.id

答案 2 :(得分:1)

您可以尝试类似

的内容
SELECT  t.*
FROM    Table t INNER JOIN
        (
            SELECT  MIN(ID) MINID,
                    Thread
            FROM    Table
            GROUP BY  Thread
        ) sub   ON  t.ID = sub.MINID 
                AND t.Thread = sub.Thread