【问题标题】:How to identify a person or id if it contains more than one row for a different column in SQL如果 SQL 中的不同列包含多行,如何识别人员或 ID
【发布时间】:2018-08-05 09:37:58
【问题描述】:

我有一张表,其中一个人在另一列中多次包含相同的值。

例如:

  person     product    portal  count    indicator
  -----------------------------------------------
      1        10        5         2        y
      1        10        6         2        y
      1        15        7         1        y


select person, count(person) over(partition by product) 
from table A 

如果一个人多次包含相同的产品,那么在这种情况下,我想识别这样的人群并想给它一些类型的指标。

在上面的示例中,产品 10 出现了多次,所以我想为所有行的人提供一个指示符。

【问题讨论】:

  • 为什么把sql中的保留关键字全部用为table_name和column_name
  • 尝试使用 distinct select * from (select person, count(distinct person) over(partition by product) cnt from table A ) where cnt>1;

标签: sql-server oracle amazon-redshift-spectrum


【解决方案1】:
WITH  C AS  
(SELECT    person, product, count(1) as Duplicate_product   
FROM  [table] A
GROUP  BY  person, product),
B AS 
(SELECT DISTINCT  person   
FROM  [table] A
GROUP BY person, product
HAVING COUNT(1) > 1)

SELECT  t.person, t.product, t.portal, 
CASE WHEN  B.person is null THEN 'N' ELSE 'Y' END  AS  indicator, ISNULL(C.Duplicate_product, 1) AS  [count] 

FROM  [table]  AS  t
INNER JOIN C ON t.person = C.person AND t.product = C.product
LEFT  JOIN B ON t.person = B.person;

【讨论】:

    猜你喜欢
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    相关资源
    最近更新 更多