我拿到了那张桌子:
id table_id ....
1 1
2 1
3 1
4 2
5 2
我想要一个查询来获取所有拥有相同table_id的最佳记录
结果:
id table_id ....
1 1
4 2
我试过了:
SELECT
id, shift_id, name_of_shift, person_in_shift,
starttime_in_shift, endtime_in_shift, table_id,
startdate, enddate, point_id
FROM
sarcshifttable
WHERE
(table_id IN (SELECT DISTINCT table_id
FROM sarcshifttable AS sarcshifttable_1))
但它带给我所有的数据,我只想要顶一个
答案 0 :(得分:1)
SELECT * FROM Table
WHERE ID IN
(SELECT ID FROM ( SELECT MIN(ID)as ID,table_id FROM Table GROUP BY table_id)x)
答案 1 :(得分:1)
他说他希望所有的专栏都回来了,所以必须这样:
SELECT
id, shift_id, name_of_shift, person_in_shift,
starttime_in_shift, endtime_in_shift, table_id,
startdate, enddate, point_id
FROM
sarcshifttable
WHERE id IN
(
SELECT MIN(id)
FROM sarcshifttable
GROUP BY table_id
)
答案 2 :(得分:0)
他们是对的 - 通过table_id选择最低(MIN()
)ID分组,您可以找到该特定表ID的最早行。
这样的事情:
SELECT
MIN(id), table_id
FROM
table1
GROUP BY
table_id
<强>更新强> 更好地理解请求,以下SQL将起作用:
SELECT
id, shift_id, name_of_shift, person_in_shift,
starttime_in_shift, endtime_in_shift, table_id,
startdate, enddate, point_id
FROM
table1
WHERE
id IN (
SELECT MIN(ID)
FROM table1 GROUP BY table_id
)
答案 3 :(得分:0)
DECLARE @What TABLE
(
id INT,
tableId INT
)
INSERT INTO @What
VALUES
(1, 1),
(2, 1),
(3, 1),
(4, 2),
(5, 2)
SELECT a.id, a.tableId
FROM
(
SELECT id, tableId, Rank() OVER (PARTITION BY tableId ORDER BY id) localRank
FROM @What
) a
WHERE a.localRank = 1
ORDER BY a.id
id tableId
1 1
4 2