【问题标题】:Exclude rows if LEFT JOIN table record count is more than one如果 LEFT JOIN 表记录数大于 1,则排除行
【发布时间】:2018-01-11 23:14:25
【问题描述】:

两个表:

表1fax_history

fax_key
1001
1002

表2 > fax_history_status

fax_key     Status
1001        NEW
1001        SUCCESS
1002        NEW

现在我需要编写一个join query,它只会返回fax_key=1002 记录,因为fax_key=1001fax_history_status 表中有不止一条记录。

所以查询结果应该是:

fax_key     status
1002        NEW

【问题讨论】:

  • 你能把样本数据框成表格吗

标签: sql sql-server database join left-join


【解决方案1】:

您可以使用having 过滤行

select a.fax_key 
from  fax_history a
inner  join  fax_history_status  b on  a.fax_key  = b.fax_key 
 group by a.fax_key
 having count(*) =1 

对于状态,您可以使用(假)聚合函数,例如:

select a.fax_key , min(b.status)
from  fax_history a
inner  join  fax_history_status  b on  a.fax_key  = b.fax_key 
 group by a.fax_key
 having count(*) =1 

【讨论】:

  • 感谢@scaisEdge 您的查询按预期返回,但是当我尝试在 select 和 group by 中添加 b.status 时,它会提供所有 3 条记录。获取fax_key 和status 是否有任何转折?
【解决方案2】:

你可以使用这样的基本查询

SELECT * FROM fax 

INNER JOIN faxstatus ON fax.faxkey=faxstatus.faxkey AND faxstatus.faxkey IN

(

SELECT faxkey  FROM faxstatus

GROUP BY faxkey

HAVING COUNT(faxkey)=1


)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    相关资源
    最近更新 更多