【问题标题】:selecting clients with only one product in SQL database在 SQL 数据库中选择只有一种产品的客户
【发布时间】:2016-07-28 10:17:15
【问题描述】:

我有一个包含 primaryCustomerID 和 PositionCode 列的表。 PriamryCustomerID 包含客户银行投资组合 ID,PositionCode 包含银行产品(WSO 和 PB)的代码。

我必须选择带有 WSO PositionCode 的客户,但不能有 PB 代码。 如果选择 PositionCode 为 WSO 的客户端,它将排除 PB 客户端,但这并不意味着客户端没有 PB。

请协助。 谢谢

【问题讨论】:

  • 请提供示例数据以显示您的数据并澄清您的问题。 10行数据就足够了。另外,显示预期的结果。
  • sql-server 和 mysql?哪一个?
  • 如果你使用 sql-server 为什么要标记 mysql? ...请删除不正确的标签

标签: mysql sql-server database sql-scripts


【解决方案1】:

这将列出所有位置代码 = 'WSO' 且没有位置代码 = 'PB' 的行的所有客户。应该适用于 sql-server 和 mySQL。

SELECT a.primaryCustomerID, a.PositionCode
from table a
where a.positionCode = 'WSO'
and not exists (select 1 from table b where b.primaryCustomerID = a.primaryCustomerID and b.positionCode = 'PB')

【讨论】:

    【解决方案2】:

    primaryCustomerID - PositionCode 1 PB 1个WSO 2 WSO 3 PB 4 PB 4 WSO

    假设这是您的表,并且您希望查询返回 Primary CustomerID - 2

    这是mysql中的示例查询(假设表名是xyz),不是优化查询,而是返回结果2,

    从 xyz 中选择 * 其中 positionCode = 'WSO' 和 PrimaryCustomerID 不在(从 xyz 中选择 PrimaryCustomerID 其中 positionCode = 'PB' )

    【讨论】:

      【解决方案3】:

      你可以使用 -

      SELECT a.primaryCustomerID, a.PositionCode
      FROM table a LEFT JOIN table b ON b.primaryCustomerID = a.primaryCustomerID
      WHERE  b.positionCode = 'PB' and a.positionCode = 'WSO' and B.primaryCustomerID IS NULL
      

      【讨论】:

      • 您应该考虑添加一些解释,说明您提出的代码/解决方案如何/为什么比其他已经发布的代码/解决方案更好(不久前)。
      猜你喜欢
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多