0

我表中的数据如下所示:

AUDTORG | SEQUENCENO | LINE | REFERENCE | AMOUNT | 
--------------------------------------------------
ADX     | 1          | 422  | Wire1     | 10     | 
ADX     | 2          | 385  | Wire2     | 10     | 
ADX     | 2          | 335  | Wire25    | 10     | 
ADX     | 2          | 335  | Transfer  | 10     | 
BMD     | 1          | 555  | Wire4     | 10     | 

我必须: 1. 连接:AUDTORG 和 SEQUENCENO 2. 计算连接字段 NewID 的出现次数。

这是我正在寻找的结果:

AUDTORG | SEQUENCENO | LINE | REFERENCE | AMOUNT | NewID  | Occurence |
-----------------------------------------------------------------------
ADX     | 1          | 422  | Wire1     | 10     | ADX1   | 1         |
ADX     | 2          | 385  | Wire2     | 10     | ADX2   | 3         |
ADX     | 2          | 335  | Wire25    | 10     | ADX2   | 3         |
ADX     | 2          | 335  | Transfer  | 10     | ADX2   | 3         |
BMD     | 1          | 555  | Wire4     | 10     | BMD1   | 1         |

这是我尝试过的代码:

SELECT *, BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar) as NewID,
count(BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar)) as Occurence
FROM ADXDAT.dbo.BKENTD

所有行必须保留。

4

2 回答 2

1

您可以使用窗口函数执行此操作:

SELECT b.*,
      (b.AUDTORG + CAST(b.SEQUENCENO AS varchar(255)) )as NewID,
      count(*) over (partition by b.AUDTORG + CAST(b.SEQUENCENO AS varchar(255)) ) as Occurence
FROM ADXDAT.dbo.BKENTD b;

over子句由窗口函数使用。在这种情况下,它计算一个组中的所有内容。组由partition by子句定义。因此,它计算具有相同新 id 值的所有内容。

于 2014-02-06T19:14:22.823 回答
1

所有行都必须保留,以便需要子查询。这将获得计数:

select BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar) as NewID, count(*) Occurence
FROM ADXDAT.dbo.BKENTD
group by BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar)

您现在拥有每个的 NewID 和计数。将其加入您的第一个语句并将其称为标准列(select * 现在是 select a.* 所以您不会得到 b.newID 字段):

SELECT a.*, BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar) as NewID, Occurence
FROM ADXDAT.dbo.BKENTD a
inner join 
(select BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar) as NewID, count(*) Occurence
FROM ADXDAT.dbo.BKENTD
group by BKENTD.AUDTORG + CAST(BKENTD.SEQUENCENO AS varchar)) b
on a.NewID = b.NewID
于 2014-02-06T18:38:35.947 回答