Sql 在合同表中查找特定客户
我正在使用MS SQL,需要帮助创建查询 我有一个名为CustomerContracts的表,其中针对特定客户的每个项目有多行 例如真实数据Sql 在合同表中查找特定客户,sql,Sql,我正在使用MS SQL,需要帮助创建查询 我有一个名为CustomerContracts的表,其中针对特定客户的每个项目有多行 例如真实数据 item cust_num x 1156 x 3924 x 7565 x 84339 x 104365 x 106066 x 107377 x 118691 y 1156 y 3924 y 7565 y 84339 y 104365 y
item cust_num
x 1156
x 3924
x 7565
x 84339
x 104365
x 106066
x 107377
x 118691
y 1156
y 3924
y 7565
y 84339
y 104365
y 106066
y 107377
因此,我需要做的是按项目编号和特定客户编号搜索表,如果该客户编号不作为该项目的记录存在,则返回该项目
因此,在这种情况下,我正在检查客户编号106066和118691的所有项目记录。如果项目不同时包含这两个客户,那么我希望将其包括在结果中,因此在这种情况下,项目X不会显示,但项目Y会显示
我想我需要做一些计数。我试过用NOT IN002003,运气不好
建议
为了满足我在这方面的尝试。我已经尝试了至少8种不同的方法,这是最新的尝试
select 'Cust Does not exist' as Status,
i.item as item,
i.description as description,
t.numcusts
From
item i inner join (select count(cust_num) as numcusts,item
from itemcust
where cust_num NOT IN ('106066','118691')
group by item) t on t.item = i.item
where i.stat = 'A' and t.numcusts > 0
order by i.item,i.description
不起作用。所以,我仍在努力解决这个问题。我能够使用Access中的嵌入查询开发一种解决方案,但无法将它创建的sql移植过来。我猜您有多个客户记录。您需要表中没有给定项记录的客户。一种方法是分组使用,并具有: 另一种方法是使用“不存在”: 第一个是客户编号列表。第二个提供这些客户的所有记录 基于编辑到问题的编辑: 问题是关于物品而不是客户。对第一种方法的修改将起作用。如果您只想要至少有一个客户的项目,请使用where子句:
谢谢你的帮助,但在喝了5杯咖啡和2张播放列表后,我终于明白了
select 'Cust Does not exist' as Status,
i.item as item,
i.description as description,expr1
From
item i RIGHT join (select itemcust.item,
sum(case when LTRIM(RTRIM(cust_num)) = '106066' or LTRIM(RTRIM(cust_num)) ='118691'then 1 else 0 end) as expr1
from itemcust
group by itemcust.item) t on t.item = i.item
where i.stat = 'A' AND expr1 <> 2
order by i.item,i.description
这给了我所有没有两个记录或实际上不止一次记录的项目。您能详细说明您到底想要什么吗?您发送的参数是什么?您能否给出一个示例,说明根据您的示例预期结果是什么?您是否也有客户表?如果存在项目y-cust_num 001,预期行为是什么。那么应该返回什么呢?我用真实的数据编辑了原始问题,要求代码必须演示最少的工作量。通过使用您的代码更新您的问题,向我们展示您的尝试。客户项目编号不是唯一的,也不是我正在搜索的内容的一部分,如果我第一次没有正确解释,我深表歉意。非常感谢。
select cc.*
from CustomerContract cc
where c.cust_num in ('001', '002') and
not exists (select 1 from CustomerContracts where cust_item_num in ('aaa'));
select cc.cust_item_num
from CustomerContracts cc
where c.cust_num in (106066, 118691)
group by cc.cust_item_num
having count(distinct c.cust_num) < 2;
select cc.cust_item_num
from CustomerContracts cc
group by cc.cust_item_num
having sum(case when c.cust_num = 106066 then 1 else 0 end) = 0 or
sum(case when c.cust_num = 118691 then 1 else 0 en) = 0;
select 'Cust Does not exist' as Status,
i.item as item,
i.description as description,expr1
From
item i RIGHT join (select itemcust.item,
sum(case when LTRIM(RTRIM(cust_num)) = '106066' or LTRIM(RTRIM(cust_num)) ='118691'then 1 else 0 end) as expr1
from itemcust
group by itemcust.item) t on t.item = i.item
where i.stat = 'A' AND expr1 <> 2
order by i.item,i.description