我必须接受卖方和客户,并将其输出到一栏中,以显示他们的城市和类型。
我的问题是:我不需要输出城市不在卖方表中的客户,反之亦然。
SELECT
ContactName, City, Type
FROM
(SELECT
'Seller' AS Type,
ContactName, City
FROM
[dbo].[Suppliers] t
GROUP BY
City, ContactName
UNION
SELECT
'Customer',
ContactName, City
FROM
[dbo].[Customers] t
GROUP BY
City, ContactName) t
GROUP BY
ContactName, City, Type
结果:
| Ivan Ivanov | Seller | Moscow |
| Piotr Petrov | Seller | Moscow |
| Ivan Romanov | Customer | Moscow |
| Johnny Bravo | Customer | London |
(假设伦敦没有卖家,因此此列不应该存在)
预期结果:仅包含信息的列,其中一个城市至少有一个按联系人姓名和城市分组的卖方和一个顾客
答案 0 :(得分:0)
这似乎像union all
和exists
:
SELECT DISTINCT c.ContactName, 'Customer' as type, c.City
FROM Customers c
WHERE EXISTS (SELECT 1 FROM Sellers s WHERE s.city = c.city)
UNION ALL
SELECT DISTINCT s.ContactName, 'Seller' as type, s.City
FROM Sellers s
WHERE EXISTS (SELECT 1 FROM Customers c WHERE c.city = s.city);
我不确定是否确实需要SELECT DISTINCT
-我不明白为什么底层表会有重复项(尽管ContactName
并不是真正用于唯一标识的好列)。但是,您的原始查询中有GROUP BY
,表明您要消除重复项。