2

这是图片的链接:

在此处输入图像描述

帮助我需要创建类似表 3 的内容。

我已经有一个查询,除了 count2 列之外,它们都包含在内,我不知道如何在查询中创建它。

这是我的查询代码:

SELECT a.rn,'',a.id, b.iddesc 
INTO #x 
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY [desc]) AS rn, * 
    FROM aa
) a, bb AS b 
WHERE b.idcon = a.id

SELECT * 
FROM #x

对不起,我不知道如何解释得很好,

4

2 回答 2

1

试试这个——

询问:

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
于 2013-06-06T10:38:35.033 回答
1

尝试这个

SELECT  
      DENSE_RANK() OVER (ORDER BY idcon) AS Count1
    , (ROW_NUMBER() OVER (PARTITION BY idcon ORDER BY idcon)) - 1 AS Count2
    , idcon
    , iddesc 
FROM Table_b b 
INNER JOIN Table_a a ON a.ID = b.idcon

这是SQLFiddle演示

于 2013-06-06T10:42:29.730 回答