我有一个如下数据库表:
创建表#temp(ID INT,Number1 INT,Number2 INT)
INSERT INTO #temp(111,123,10)
INSERT INTO #temp(111,223,10)
INSERT INTO #temp(111,323,10)
INSERT INTO #temp(112,123,11)
INSERT INTO #temp(112,223,11)
INSERT INTO #temp(112,333,11)
INSERT INTO #temp(113,124,12)
INSERT INTO #temp(113,126,12)
INSERT INTO #temp(114,128,121)
我一直在研究查询,但仍然没有运气。我希望返回以下结果:
ID Number1 Number2
111 323 10
112 333 11
113 126 12
114 128 121
在结果集中,需要返回具有相同ID值的列号Number1的最大值的行。
答案 0 :(得分:1)
这个SQL修复了你的SQL :-)我认为你会回答你的答案:
DECLARE @temp table (ID INT, Number1 INT, Number2 INT);
INSERT INTO @temp (ID,Number1, Number2) VALUES (111, 123, 10)
INSERT INTO @temp (ID,Number1, Number2) VALUES (111, 223, 10)
INSERT INTO @temp (ID,Number1, Number2) VALUES (111, 323, 10)
INSERT INTO @temp (ID,Number1, Number2) VALUES (112, 123, 11)
INSERT INTO @temp (ID,Number1, Number2) VALUES (112, 223, 11)
INSERT INTO @temp (ID,Number1, Number2) VALUES (112, 333, 11)
INSERT INTO @temp (ID,Number1, Number2) VALUES (113, 124, 12)
INSERT INTO @temp (ID,Number1, Number2) VALUES (113, 126, 12)
INSERT INTO @temp (ID,Number1, Number2) VALUES (114, 128, 121)
SELECT DISTINCT T1.ID, T1.Number1, T1.Number2
FROM @temp T1
JOIN @temp T2 ON T1.ID = T2.ID AND T1.Number1=(SELECT MAX(Number1) FROM @temp T3 WHERE T3.ID=T1.ID)
一切顺利, 迈克尔
答案 1 :(得分:0)
SELECT ID, Max(Number1) as Number1, Number2 FROM #temp group by ID, Number2
我相信你正在寻找GROUP
条款。它返回:
111 323 10
112 333 11
113 126 12
114 128 121
感谢@MichaelMoreno指出。我认为这是OP的一个错字,我没有把它作为解决方案发布。他真的在寻求通往SELECT
的道路。这是更正后的代码:
Create table #temp(ID INT, Number1 INT, Number2 INT)
INSERT INTO #temp values(111, 123, 10)
INSERT INTO #temp values(111, 223, 10)
INSERT INTO #temp values(111, 323, 10)
INSERT INTO #temp values(112, 123, 11)
INSERT INTO #temp values(112, 223, 11)
INSERT INTO #temp values(112, 333, 11)
INSERT INTO #temp values(113, 124, 12)
INSERT INTO #temp values(113, 126, 12)
INSERT INTO #temp values(114, 128, 121)