SQL。如何使用MIN和GROUP BY选择多行

时间:2014-06-16 04:30:42

标签: sql sql-server tsql

ID UserId Name   Amount  RewardId
----------------------------
1  1      James  10.00   1
2  1      James  10.00   2
3  1      James  10.00   3
4  2      Dave   20.00   1
5  2      Dave   20.00   3
6  3      Lim    15.00   2

我正在尝试插入另一张桌子,这是我正在努力的结果:

Tbl1ID  RewardId
------------------
1       1
1       2
1       3
4       1
4       3
6       2

我正在尝试获取每个人的MIN(ID)并选择属于该人的所有RewardId。

3 个答案:

答案 0 :(得分:3)

你可以做一个简单的自我加入来获得每个userid / rewardid组合的最小id值;

SELECT MIN(a.id) Tbl1ID, b.RewardId
FROM mytable a
JOIN mytable b
  ON a.name = b.name
GROUP BY b.userid, b.rewardid
ORDER BY tbl1id, rewardid;

An SQLfiddle to test with

答案 1 :(得分:0)

如果您运行的是SQL Server 2008+,则可以使用Window Function来简化它。

INSERT INTO AnotherTable (Tbl1ID, RewardID)
SELECT MIN(ID) OVER (PARTITION BY Name),
       RewardID
FROM   SourceTable

答案 2 :(得分:0)

试试这个

SELECT tbl1id,RewardID From
table1 S JOIN
(
SELECT MIN(ID) as tbl1id,Name FROM table1 GROUP BY Name
) T ON T.Name = S.Name
ORDER BY tbl1id

<强> FIDDLE DEMO

输出:


    Tbl1ID  RewardId
    ----------------
    1       1
    1       2
    1       3
    4       1
    4       3
    6       2

如果你想插入新表,那就试试吧

Insert into Newtable (tbl1id,RewardID)
SELECT tbl1id,RewardID from
table1 S JOIN
(
SELECT MIN(ID) as tbl1id,Name
FROM table1
GROUP BY Name
) T ON T.Name = S.Name

ORDER BY tbl1id;

<强> FIDDLE DEMO