PostgreSQL在行中找到不一致记录

时间:2013-10-02 10:11:56

标签: sql postgresql

我有一个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     |  

6 个答案:

答案 0 :(得分: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_ID说Sarah有多达2个电话号码而Tom只有1个不同的号码。

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

最终输出:

SALESMAN PHONE FREQ DISTINCT_PHONE_NUM_ID 
Sarah   1111    1   2 

答案 1 :(得分: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;

如果可行则会很有趣。

答案 2 :(得分:0)

SELECT  *
FROM lutser_table lt
WHERE EXISTS (
   SELECT * FROM lutser_table ex
   WHERE ex.Salesman = lt.Salesman
   AND ex.Phone <> lt.Phone
   );

答案 3 :(得分:0)

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

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

SQLFiddle demo

答案 4 :(得分:0)

您也可以通过/拥有一个简单的组来查询结果:

select salesman
from sales
group by salesman
having count(distinct phone) > 1

答案 5 :(得分:0)

选择*来自x所在的Salesman(选择销售员 来自table_name 按推销员分组 有计数(不同的电话)&gt; 1)

我希望这会给出