得到一行sql

时间:2012-09-13 08:21:31

标签: sql sql-server

我有下表

Id          Stack
------------------
1             a
1             b
2             c
2             d

我想得到下表结果。

Id          Stack
------------------
1             a
2             c

我使用DISTINCT但它不起作用 我该怎么做 ? 有什么解决方案可以使用group by?

4 个答案:

答案 0 :(得分:2)

CREATE table sampletb(id int, stack varchar(10));

INSERT into sampletb values(1,'a');
INSERT into sampletb values(1,'b');
INSERT into sampletb values(2,'c');
INSERT into sampletb values(2,'d');

SELECT * FROM sampletb;

id          stack
----------- ----------
1           a
1           b
2           c
2           d


SELECT id,
       stack,
       row_number() over (partition by id order by stack) as row_number
from   sampletb;

此查询将为您提供这样的结果。

id          stack      row_number
----------- ---------- --------------------
1           a          1
1           b          2
2           c          1
2           d          2

现在将上述查询作为子查询并获取列 row_number=1会给出你想要的欲望输出。

select id,stack from 
       (
       SELECT id,
              stack,
              row_number() over (partition by id order by stack) as row_number 
       FROM   sampletb) x
where  x.row_number=1;

id          stack
----------- ----------
1           a
2           c

答案 1 :(得分:1)

select id,stack from (
select id , stack  , row_number() over (partition by id order by stack) as rn
) k where rn=1

答案 2 :(得分:1)

我不确定您需要应用的确切逻辑,但这会返回您发布的结果:

SELECT  ID, MIN(Stack) AS Stack
FROM    T
GROUP BY ID

如果您的DBMS允许,您可以使用ROW_NUMBER函数使用更高级的逻辑(在问题中没有标记)

SELECT  ID, Stack
FROM    (   SELECT  ID,
                    Stack,
                    ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Stack) AS RowNumber
            FROM    T
        ) t
WHERE   RowNumber = 1

答案 3 :(得分:0)

这应该有帮助

select Id, min(Stack) from <TABLE_NAME>
group by Id