我们可以让用户拥有多个valueID
个。在SQL Server中,我尝试提取valueID
3
但valueID
1
和2
的所有用户。因此,表格A
会有user
列和valueID
列。
如何编写SQL查询来执行此操作?
此外,有什么好的资源可以让我的SQL查询技能达到标准?
非常感谢。
答案 0 :(得分:1)
尝试:
SELECT user
FROM A outer
WHERE valueID = 3
AND NOT EXISTS
(
SELECT 1
FROM A inner
WHERE
(
valueID = 1
OR valueID = 2
)
AND inner.user = outer.user
)
答案 1 :(得分:0)
此查询将返回具有值(3和1)或(3和2)或仅3
的所有用户select user
from mytable t1
where valueId = 3
and (select count(distinct valueId)
from mytable t2 where t2.user = t1.user
and valueId IN (1,2)) < 2
答案 2 :(得分:0)
这是另外一个....(所有用户都是valueid = 3而没有别的东西)
SELECT [USER]
FROM A
GROUP BY [USER]
HAVING MAX(CASE WHEN valueid = 3 THEN 0 when valueid IN (1,2) THEN 1 END) = 0;
答案 3 :(得分:0)
如果您指的是值为3的用户,除了那些值为1和2的用户外,还有一种简单的方法可以获得您的问题
Select s.UserID From SomeTable s
Where s.UserID NOT In
(select s1s.UserID From SomeTable s1s
inner join SomeTable s2s On s1s.UserID = s2s.UserID
Where s1s.ValueId = 1 And s2s.ValueId = 2)
或者
Select s.UserID From SomeTable s
Left Join
(select s1s.UserID From SomeTable s1s
inner join SomeTable s2s On s1s.UserID = s2s.UserID
Where s1s.ValueId = 1 And s2s.ValueId = 2) both
Where both.userID is null
答案 4 :(得分:-1)
我不确定您的表格结构是什么,但根据列名称,以下查询可能会起作用...
SELECT user, valueID
FROM users
WHERE valueID = 3