显示重复的行(该行的所有列),其中所有列都是重复的,除了一列

时间:2018-03-23 04:53:43

标签: sql teradata

在下表中,我需要选择重复记录,其中所有列都是重复的,但特定周的客户类型和价格除外。

例如

Week Customer  Product  Customer Type   Price
1    Alex      Cycle    Consumer        100
1    Alex      Cycle    Reseller        101
2    John      Motor    Consumer        200
3    John      Motor    Consumer        200
3    John      Motor    Reseller        201

我正在使用以下查询,但此查询并未向我显示客户类型,它只显示组合的消费者数量(*)。

select Week, Customer, product, count(distinct Customer Type)
from table
group by Week, Customer, product
having count(distinct Customer Type) > 1

我想看下面的结果,它显示了重复的值,而不仅仅是重复行的计数(*)。我试图在特定的一周内看到客户分配给多个客户类型的产品,同时向我显示所有列。如果价格不同,这并不重要。

Week Customer  Product  Customer Type   Price
1    Alex      Cycle    Consumer        100
1    Alex      Cycle    Reseller        101
3    John      Motor    Consumer        200
3    John      Motor    Reseller        201

由于

沙基

5 个答案:

答案 0 :(得分:1)

Select 
    c.CustomerNumber,
    c.CustomerName,
    c.DueDate,
    c.ChequeNumber,
    c.Amount,
    c.Status,
    n.NextDate,
    a.tel,
    a.tel2,
    a.mobile 
from 
    currentCustemerChequeTable c 
    inner join NewTDate n on c.CustomerNumber = n.CustomerNO 
    inner join CustomerAddressTable a on c.CustomerNumber = a.code
ORDER BY c.CustomerNumber 
  OFFSET 10 ROWS
  FETCH NEXT 20 ROWS ONLY

注意:请将“Your_Table_Name”替换为确切的表名并尝试。

答案 1 :(得分:0)

使用通用SQL实现此目的的一种方法是使用"派生表"像这样:

select x.*
from tablex x
inner join (
    select Week, Customer, Product 
    from tablex 
    group by Week, Customer, Product
    having count(*) > 1
    ) d on x.Week = d.Week and x.Customer = d.Customer and x.Product = d.Product

答案 2 :(得分:0)

您可以使用DISTINCT之类的

来实现这一目标
select DISTINCT Customer,Product,Customer_Type,Price from Your_Table_Name

将寻找DISTINCT组合 注意:此查询是否为SQL Server

答案 3 :(得分:0)

根据您粘贴的预期结果,您似乎并不关心本周。 如果你有一个ID(增量PK),它将更简单,如下面

从不在ID的表中选择* (按客户,产品,具有计数(*)> 1的CustomerType从表格组中选择最大(ID)

这是在MySQL上测试的。你有ID栏吗? 如果您没有ID列,请尝试以下操作:

按客户,产品,客户类型从设备组中选择最大(周)周,客户,产品,客户类型,最大(价格);

我还没有验证过这个。

答案 4 :(得分:0)

这将返回您的预期结果集:

select *
from table
-- Teradata syntax to filter the result of an OLAP-function
-- (similar to HAVING after GROUP BY)
qualify
   count(*)
   over (partition by Week, Customer, product) > 1

对于其他DBMS,您需要嵌套查询:

select *
from
 (
    select ..., 
       count(*)
       over (partition by Week, Customer, product) as cnt
    from table
 ) as dt
where cnt > 1

编辑:

重新阅读上面的描述后,选择可能不是您想要的,因为它也会返回单一类型的行。然后切换到:

select *
from table
-- Teradata syntax to filter the result of an OLAP-function
-- (similar to HAVING after GROUP BY)
qualify -- at least two different types:
   min(Customer_Type) over (partition by Week, Customer, product)
<> max(Customer_Type) over (partition by Week, Customer, product)