我该如何编写这个SQL查询?

时间:2009-07-28 18:09:29

标签: sql

我有一个表,记录链接到父项的子项的历史记录,有两列:

  • 的ParentId
  • childID的

一些示例数据如下所示:

ParentId - ChildId
001 - 001
001 - 001
001 - 001
001 - 002
001 - 002
001 - 002
001 - 003
001 - 003
001 - 003
001 - 003
001 - 004
001 - 004
001 - 005
001 - 005
001 - 005
001 - 005

我需要为给定的ParentId选择具有最高值ChildId的所有行。所以在上面的例子中,我需要查询返回以下行,给定输入参数'@ parentId = 001':

001 - 005
001 - 005
001 - 005
001 - 005

感谢您的帮助!

5 个答案:

答案 0 :(得分:5)

这要做到这一点:

SELECT * FROM MyTable
WHERE parentId = '001'
AND childId = (SELECT MAX(childId) FROM MyTable WHERE parentId = '001')

答案 1 :(得分:1)

这个怎么样?

SELECT ParentID, MAX(ChildID) AS ChildID
FROM TableName
GROUP BY ParentID

更新以修改错过的要求以返回所有行:

测试数据

-- Populate Test Data
CREATE TABLE #table (
  ParentID varchar(3) NOT NULL, 
  ChildID varchar(3) NOT NULL
)

INSERT INTO #table VALUES ('001','001')
INSERT INTO #table VALUES ('001','001')
INSERT INTO #table VALUES ('001','001')
INSERT INTO #table VALUES ('001','002')
INSERT INTO #table VALUES ('001','002')
INSERT INTO #table VALUES ('001','002')
INSERT INTO #table VALUES ('001','003')
INSERT INTO #table VALUES ('001','003')
INSERT INTO #table VALUES ('001','003')
INSERT INTO #table VALUES ('001','003')
INSERT INTO #table VALUES ('001','004')
INSERT INTO #table VALUES ('001','004')
INSERT INTO #table VALUES ('001','005')
INSERT INTO #table VALUES ('001','005')
INSERT INTO #table VALUES ('001','005')
INSERT INTO #table VALUES ('001','005')

<强> 结果

-- Return Results
DECLARE @ParentID varchar(8)
SET @ParentID = '001'

SELECT T1.ParentID, T1.ChildID
FROM #table T1
JOIN (
    SELECT Q1.ParentID, MAX(Q1.ChildID) AS ChildID
    FROM #table Q1
    GROUP BY ParentID
) ParentChildMax ON ParentChildMax.ParentID = T1.ParentID AND ParentChildMax.ChildID = T1.ChildID
WHERE T1.ParentID = @ParentID

注意:此解决方案的性能与WHERE子句中使用以下语句的已接受解决方案(根据SQL Server探查器)相同。但我更喜欢我的解决方案,因为它对我来说似乎更干净,并且可以很容易地扩展到包含其他ParentID是必需的。 (例如,报告目的。)

(SELECT MAX(childId) FROM #table WHERE parentId = @ParentID)

答案 2 :(得分:1)

SELECT *
FROM TABLENAME
WHERE parentId = '001'
AND childid = (select MAX (ChildId) 
               from TABLENAME
               where parentId = '001')

答案 3 :(得分:0)

SELECT *
FROM table_name
在哪里ParentId = @parentId
GROUP BY ParentId
具有ChildId = MAX(ChildId)

答案 4 :(得分:-1)

为了满足表格中的多个父母,以下内容应该有所帮助

select parentId, max(childid) as ChildId
from <table_name>
group by parentId
相关问题