如何获得除一列外所有值均相同的两行

时间:2019-04-29 12:26:33

标签: sql ssms

我想获得所有列(列ID除外)具有相同值的所有行。我尝试使用where语句来做到这一点,但我仍然可以看到所有其他行。

SELECT 
a.strBedrijf,a.IdLeverancier,a.strLevFactNr, a.Id, a.dtmFactuur, a.fBedragInc, be.bDeleted,

'https://documents.blabla/' + (select top(1) textval from tblsettings where id='Workflow_customerid') + '/?p=PurchaseInvoiceDetails&Id=' + a.id  as Url,

case when be.bDeleted = 'JA' then 'NEE'

when be.bDeleted = 'NEE' then 'JA' end as AdministratieActief

FROM   tblfacturen A, tblfacturen B

        join tblBedrijven be on strBedrijf=be.Id

WHERE

be.bDeleted = 'NEE'  and

A.idleverancier = B.idleverancier

    AND A.strLevFactNr=B.strLevFactNr

    AND A.dtmFactuur=B.dtmFactuur

 AND A.fBedragInc=B.fBedragInc

   AND A.ID != B.ID

AND a.bDeleted ='NEE'

AND b.bDeleted ='NEE'

and a.strlevfactnr not like 'corr%'

group by A.strBedrijf,a.IdLeverancier,a.strLevFactNr, a.Id, a.dtmFactuur,     a.fBedragInc, be.bDeleted

这是我的输出:

L014909 227330  e2f02668-b1ac-416f-809d-a9a100c689c2    2018-11-23 00:00:00.000 288 NEE JA
L021960 24614767    48cf2ed2-160f-43a2-8bb0-a9a0006f8cf1    2018-11-16 00:00:00.000 232,05  NEE JA
L1630   297373  4200e599-f7ec-45fb-a003-a3570096289c    2014-06-24 00:00:00.000 484,75  NEE JA
L1630   297373  bfccef8d-dccb-4263-bcc7-a355006073de    2014-06-24 00:00:00.000 484,75  NEE JA
L017875 3493813 8e112901-13ea-4ed3-abf8-a9b200756b98    2018-12-07 00:00:00.000 1832,47 NEE JA

但我想获得以下输出:

L1630   297373  4200e599-f7ec-45fb-a003-a3570096289c    2014-06-24 00:00:00.000 484,75  NEE JA
L1630   297373  bfccef8d-dccb-4263-bcc7-a355006073de    2014-06-24 00:00:00.000 484,75  NEE JA

2 个答案:

答案 0 :(得分:0)

您需要将表本身与所有列相等且id不相等的表连接起来,如以下示例所示

create table test (
    id int,
    col1 int,
    col2 int
)

SELECT t1.*
FROM test t1
JOIN test t2 ON t1.col1 = t2.col1 AND t1.col2 = t2.col2 AND t1.id <> t2.id

答案 1 :(得分:0)

  我想获得所有列(列ID除外)具有相同值的所有行。

使用窗口功能:

select t.*
from (select t.*, count(*) over (partition by col1, col2) as cnt  -- list all columns here
      from t
     ) t
where cnt >= 2
order by col1, col2;