表格
内容
要撤退的字段
c.Name,cg.Name
问题
我想显示所有在“销售”组中的客户,并在cg.Name中显示“销售”值。但是,然后不在“销售”组中的所有客户都显示客户名称,但保留组名称“空白”。
尝试
SELECT c.Name, cg.Name, [NotInGroup].group
FROM Customer c
LEFT JOIN CustomerGroup cg on cg.CustID= c.ID
OUTER APPLY(
SELECT c2.Name, cg2.Name as [group]
FROM Customer c2
LEFT JOIN CustomerGroup cg2 on cg2.CustID= c2.ID
WHERE cg1.Name != 'Sales'
) as [NotInGroup]
WHERE cg.Name = 'Sales'
所需结果
谢谢。
答案 0 :(得分:2)
一种方法使用left join
:
SELECT c.Name, cg.Name,
FROM Customer c LEFT JOIN
CustomerGroups cg
ON cg.custid = c.id AND
cg.Name = 'Sales';
请注意,对Sales
的过滤位于ON
子句中。这很重要,除非您要为每个客户和客户所属的每个组单独分配一行。
还要注意加入条件。
答案 1 :(得分:0)
SELECT c.Name, CASE WHEN cg.Name ='Sales' the 'Sales' else '' end
FROM Customer c
LEFT JOIN CustomerGroup cg on cg.ID = c.ID
答案 2 :(得分:0)
SELECT c.[Name]
,ISNULL(cg.[Name],'') AS GroupName
FROM Customer c
LEFT JOIN CustomerGroup cg ON cg.ID = c.ID AND cg.[Name] = 'Sales'
答案 3 :(得分:0)
只需使用左联接和coalesce()
。
SELECT c.name,
coalesce(cg.name, '')
FROM customer c
LEFT JOIN customergroup cg
ON cg.id = c.id
AND cg.name = 'Sales';
但是,我不确定customergroup.id
是否引用customer.id
。您可能需要将cg.id
替换为实际引用客户的列。