试试这个——
询问:
DECLARE @table_a TABLE (id INT, [desc] NVARCHAR(50))
INSERT INTO @table_a (id, [desc])
VALUES
(221, 'aaa'),(222, 'sss'),
(223, 'ddd'),(225, 'fff')
DECLARE @table_b TABLE (idcon INT, iddesc NVARCHAR(50))
INSERT INTO @table_b (idcon, iddesc)
VALUES
(221, 'zxc'),(221, 'sad'),
(221, 'fdfg'),
(222, 'asd'),(222, 'vcx'),
(223, 'zxc'),(223, 'asd'),
(224, 'cxv'),(224, 'asd'),
(225, 'zcx'),(225, 'asd'),
(225, 'qwe'),(225, 'wer')
SELECT
idcon
, [desc] = iddesc
, count1
, count2 = ROW_NUMBER() OVER (PARTITION BY id ORDER BY [desc]) - 1
FROM (
SELECT *, count1 = ROW_NUMBER() OVER (ORDER BY id)
FROM @table_a
) a
JOIN @table_b ON id = idcon
结果:
idcon desc count1 count2
------- ------ ------- -------
221 zxc 1 0
221 sad 1 1
221 fdfg 1 2
222 asd 2 0
222 vcx 2 1
223 zxc 3 0
223 asd 3 1
225 zcx 4 0
225 asd 4 1
225 qwe 4 2
225 wer 4 3