我有一个sql server查询问题。我有一张如下表。给存储过程一个参数,我需要在我想要的列表中查询相互的CustomFields。例如,如果ListID被赋予1和2以及3,那么结果表将具有在这种情况下给我'FullName'的列,因为在所有三个ID中只有'FullName'。我做了那个以某种方式解决了这个问题,但寻找更好,更精确的练习。感谢
SELECT DISTINCT(CustomField)
FROM CustomFields a
WHERE EXISTS (
SELECT count(*)
FROM CustomFields b
WHERE a.CustomField = b.CustomField
HAVING count(*)>2
)
ORDER BY a.CustomField
CustomField ListID
PhoneNumber 1
Unvan 1
FullName 2
Surname 2
Regiob 2
FullName 3
BirthPlace 3
FullName 1
答案 0 :(得分:3)
这是一种更常见的方法来查找第1,2和3组中的CustomField:
SELECT CustomField
FROM CustomFields
WHERE ListID in (1,2,3)
GROUP BY
CustomField
HAVING COUNT(DISTINCT ListId) = 3
不需要子查询,where
子句在group by
之前过滤掉不感兴趣的组。
答案 1 :(得分:2)
我正在考虑更多这方面的内容,这些内容改编自@Andomar并且更为通用。
CREATE TYPE ListIdType AS TABLE (
ListId int PRIMARY KEY
);
GO
CREATE PROCEDURE S
@ListIdTable ListIdType READONLY
AS BEGIN SET NOCOUNT ON;
SELECT CustomField
FROM CustomFields
WHERE ListID in (SELECT ListId FROM @ListIdTable)
GROUP BY
CustomField
HAVING COUNT(DISTINCT ListId) = (SELECT COUNT(ListId) FROM @ListIdTable)
END;