SQL添加一个额外的列,用于计算特定列的重复值

时间:2014-10-23 17:08:04

标签: sql sql-server-2008-r2 count distinct

我好像有休息日,似乎无法让这个查询正常工作。

最初我没有使用DISTINCT的查询包括重复2行:

STAT       SHNO      UPDD         UPDT       ORDERNO 
40       ASN123    20141022   150048       40303020
30       ASN124    20141022   150048       40303021
30       ASN124    20141022   150048       40303021
40       ASN123    20141022   150048       40303020
30       ASN125    20141022   150048       40303021

我将查询更改为包含DISTINCT:

SELECT DISTINCT  
    STAT, SHNO, UPDD, UPDT, ORDERNO
FROM   
    BLUEWATER                                  

我现在得到了所需的结果集:

STAT         SHNO         UPDD        UPDT      ORDERNO
30         SHN124       20141022      150048      40303021
30         SHN125       20141022      150048      40303021
40         SHN123       20141022      150048      40303020

但是,我要做的是使用COUNT在我的结果中生成一个列,该列计算ORDERNO不唯一的行并希望获得以下内容:

STAT         SHNO         UPDD        UPDT      ORDERNO      ORDERNOCOUNT     
30         SHN124       20141022      150048    40303021      2                
30         SHN125       20141022      150048    40303021      2                
40         SHN123       20141022      150048    40303020      1                

1 个答案:

答案 0 :(得分:1)

我只是使用group by和COUNT()OVER ...你在使用什么版本?

SELECT STAT, SHNO, UPDD, UPDT, ORDERNO, 
       COUNT(*) OVER (PARTITION BY ORDERNO) AS ORDERNOCOUNT
FROM BLUEWATER     
GROUP BY STAT, SHNO, UPDD, UPDT, ORDERNO

作为子选择

SELECT gsub.STAT, gsub.SHNO, gsub.UPDD, gsub.UPDT, gsub.ORDERNO, sub.c AS ORDERNOCOUNT
FROM 
(
   SELECT STAT, SHNO, UPDD, UPDT, ORDERNO
   FROM BLUEWATER
   GROUP BY STAT, SHNO, UPDD, UPDT, ORDERNO
) gsub
JOIN (
   SELECT ORDERNO, COUNT(*) as c
   FROM BLUEWATER
   GROUP BY ORDERNO
) as sub ON gsub.ORDERNO = sub.ORDERNO