我需要在进行 GROUP BY 时找出值来自的行 ID。
首先创建并填充一个“播放对象”
-- vertical coalesce with row-source of value :) instead of column-source of value as in horizontal coalesce :)
CREATE TABLE #TBL(ID INT, GR INT, A INT, B INT)
INSERT INTO #TBL
SELECT 1,1,1,NULL
UNION ALL SELECT 2,1,NULL,2
UNION ALL SELECT 3,1,NULL,3
UNION ALL SELECT 4,2,2,NULL
UNION ALL SELECT 5,2,NULL,NULL
UNION ALL SELECT 6,2,6,NULL
选择最小值很简单:
SELECT GR, MIN(A) A, MIN(B) B,
'Which first available row did A come from?' A_ID,
'Which first available row did B come from?' B_ID
FROM #TBL
GROUP BY GR
但回答问题不是!
我试图做子查询,但由于值来自不同的行,它不起作用:
SELECT a.*
from #TBL a
join (
SELECT GR, MIN(A) A, MIN(B) B,
'Which row did A come from?' A_ID,
'Which row did B come from?' B_ID
FROM #TBL
GROUP BY GR) b on a.GR = b.GR and a.A = b.A and a.B = b.B
--DROP TABLE #TBL
请帮忙。