1

我有一个 PostgreSQL 表如下:

   PO Num  |  Salesman |   Phone   |  
-----------+-----------+-----------+
 PO13175   |  Sarah    |  111      |
 PO13203   |  Sarah    |  1111     |  
 PO12203   |  Tom      |  222      |  
 PO8656    |  Tom      |  222      |  
...
(n rows)   

推销员和电话号码是成对的,我如何识别第 2 行这样的差异?(莎拉应该有一个和汤姆一样的电话号码)

我曾尝试使用“分区”

select *,Row_number() over (partition by Salesman,Phone) as row from table
where row>1;

但它并没有给我想要的东西。

我想得到如下记录:

   PO Num  |  Salesman |   Phone   |  
-----------+-----------+-----------+
 PO13175   |  Sarah    |  111      |
 PO13203   |  Sarah    |  1111     |  
4

6 回答 6

1

您使用 Windowing 功能是正确的。以下将返回 Sarah 的电话号码不一致

select a.*
from
(select 
salesman
,phone
,count(*) as freq
,count(*)over(partition by salesman order by phone) as distinct_phone_num_id
from mydata /*replace this with your actual tablename*/
group by 
salesman
,phone) as a
inner join
(select distinct salesman from mydata) as b
on a.salesman=b.salesman and a.distinct_phone_num_id>1
;

说明:该a表将首先计算所有可能的salesman&phone组合。然后count(*)over(partition by salesman order by phone)将连续枚举为每个推销员找到的每个不同的电话号码。

SALESMAN PHONE FREQ DISTINCT_PHONE_NUM_ID 
Sarah   111     1   1 
Sarah   1111    1   2 
Tom     222     2   1 

因此,您可以在上面看到,DISTINCT_PHONE_NUM_IDSarah 最多有 2 个电话号码,而 Tom 只有 1 个不同的号码。

的目的inner join是为您salesman提供电话号码不一致的列表。

最终输出:

SALESMAN PHONE FREQ DISTINCT_PHONE_NUM_ID 
Sarah   1111    1   2 
于 2013-10-02T10:19:13.703 回答
0
SELECT  *
FROM lutser_table lt
WHERE EXISTS (
   SELECT * FROM lutser_table ex
   WHERE ex.Salesman = lt.Salesman
   AND ex.Phone <> lt.Phone
   );
于 2013-10-02T10:24:24.770 回答
0

select * from x where Salesman in(select salesman from table_name group by salesman with count(distinct phone) > 1)

我希望这会给

于 2013-10-03T05:03:11.950 回答
0
SELECT *
FROM tbl t1
JOIN tbl t2
  ON (t1.salesman = t2.salesman AND t1.phone <> t2.phone AND t1.po_num <> t2.po_num)
GROUP BY t1.salesman;

如果可行的话会很有趣。

于 2013-10-02T10:22:15.293 回答
0

您也可以使用简单的 group by / having 来查询结果:

select salesman
from sales
group by salesman
having count(distinct phone) > 1
于 2013-10-02T12:52:24.247 回答
0

您应该 NORMALIZE 您的数据库架构以避免此类问题:

select * from t as t1
where EXISTS(select 1 from t 
                where t.salesman=t1.salesman 
                  and t.phone<>t1.phone)

SQLFiddle 演示

于 2013-10-02T11:01:03.597 回答