SQL 查询答案



使用SQL,我选择以下内容:

SELECT itemid, custid, email FROM tableA;  

我可以为每个Custid有多个itemid,并且只有一封电子邮件,例如

itemid1, custid, email
itemid2, custid, email
itemid3, custid, email

我如何只向指定他有 3 个 itemid 的客户发送一封电子邮件?

谢谢

select count(itemid), custid, email 
from tableA
group by email, custid

在澄清 OP 正在连接表并希望在一行中使用电子邮件地址的项目列表后,我们有以下查询:

select b.custid, b.email, 
   itemids = STUFF((select ',' + itemid 
             from tableA a 
             where a.custid = b.custid FOR XML PATH('')), 1, 1, '') 
from tableB b

这将做到这一点,但如果您需要有关项目的更多信息,我强烈建议您获取客户列表,然后循环浏览它们以获取项目信息。

你可以对你所有的custidemail使用这样的函数:

ALTER        FUNCTION itemrow(@custid int, @email varchar(max)) --check your datatypes
RETURNS VARCHAR(max) AS
BEGIN
  DECLARE @itemrow VARCHAR(max)
  SELECT  @itemrow = COALESCE(@itemrow + ', ', '') + COALESCE(itemid,'')
  FROM tableA
  where email = @email
  and custid = @custid
return @itemrow
END

最新更新