查询所有孩子都成对/重复的父母

时间:2018-08-24 15:16:03

标签: sql sql-server

我正在寻找查询的方向,以获取ID的位置,对于每笔交易,返回TransDd的所有子对象(可以说product,qty,price)具有成对/重复值的地方。此处的示例:

TransID      Product   QTY  Price  
1            a         2    1.0
1            a         2    1.0
1            b         3    2.5
2            a         1    1.0
2            a         1    1.0
2            b         2    2.0
2            b         2    2.0
3            a         5    2.0
3            a         4    3.0
4            a         1    2.0
4            a         1    2.0
4            b         2    2.0
4            b         2    2.0
4            c         1    1.0

在此示例中,将仅返回transID 2。

到目前为止,我仍然坚持

select transid, product, qty, price
     , row_number() over (partition by transid, product, qty, price order by transID desc) rk 
from x

但是我认为我在那儿走错了路。欣赏任何方向。

6 个答案:

答案 0 :(得分:3)

您可以使用count()代替row_number()来做到这一点:

select transid
from (select x.*,
             count(*) over (partition by transid, product, qty, price) as cnt 
      from x
     ) x
group by transid
having min(cnt) > 1;

但是,这有点过头了,您也可以在子查询中使用group by

select transid
from (select transid, product, qty, price, count(*) as cnt
      from x
      group by transid, product, qty, price
     ) x
group by transid
having min(cnt) > 1;

答案 1 :(得分:3)

如果我的理解正确,这应该为您提供所需的答案:

CREATE TABLE dbo.SampleData (TransID int, Product char(1), Qty int, Price decimal(2,1));
INSERT INTO dbo.SampleData (TransID,
                            Product,
                            Qty,
                            Price)
VALUES (1,'a',2,1.0),
       (1,'a',2,1.0),
       (1,'a',2,1.0),
       (1,'b',3,2.5),
       (2,'a',1,1.0),
       (2,'a',1,1.0),
       (2,'b',2,2.0),
       (2,'b',2,2.0),
       (3,'a',5,2.0),
       (3,'a',4,3.0);

WITH Counts AS (
    SELECT TransID,Product,Qty,
           COUNT(*) AS Dups
    FROM dbo.SampleData
    GROUP BY TransID, Product, Qty)
SELECT TransID
FROM Counts
GROUP BY TransID
HAVING MIN(Dups) >= 2;

DROP TABLE dbo.SampleData;

答案 2 :(得分:0)

使用NOT EXISTS并检查不存在没有重复行的ID。

答案 3 :(得分:0)

select TransID 
from table
except
select TransID
from table 
group by TransID, Product, QTY, Price 
having count(*) = 1

答案 4 :(得分:0)

尝试此查询:

select transid,
       product, 
       qty, 
       price
from (
    select transid,
           product, 
           qty, 
           price,
           count(*) over (partition by transid, product) cntproduct,
           count(*) over (partition by transid, qty) cntqty,
           count(*) over (partition by transid, price) cntprice
    from my_table
) a where cntprice > 1 and cntproduct > 1 and cntqty > 1

答案 5 :(得分:-2)

SELECT TransID FROM
(
    SELECT COUNT(*) AS Count, TransID, Product, QTY, Price
    FROM x
    GROUP BY TransID, Product, QTY, Price
    HAVING Count = 2
) AS Table1
NOT IN
SELECT TransID FROM
(
    SELECT COUNT(*) AS Count, TransID, Product, QTY, Price
    FROM x
    GROUP BY TransID, Product, QTY, Price
    HAVING Count = 1
) AS Table2

然后读取TransID。完成!