我的表是
ID ATTRID VALSTR
1771373 1 1234
1771373 3 510
1771373 7 2016
1771373 8 05
1777623 3 5003
1777623 7 2016
1777623 8 05
1778103 3 520
1778103 7 2016
1778103 8 06
我想选择条件
AttrId = 3 AND ValStr = 510
AttrId = 7 AND ValStr = 2016
AttrId = 8 AND ValStr = 05
我写了这个,但是没有正确运行
SELECT *
FROM Table
WHERE ((AttrID = 3 AND ValStr ='510') OR
(AttrID = 7 AND ValStr ='2016') OR
(AttrID = 8 AND ValStr ='05')
) AND
DefID = 1375552
如何撰写此查询?能帮帮我吗?
答案 0 :(得分:3)
我想看到AttrID = 3 AND ValStr ='510'AttrID = 7 AND ValStr ='2016' AttrID = 8 AND ValStr ='05'同时3条件为真所以想要 仅参见ID 1771373
我认为这就是你所追求的。是吗?
SELECT *
FROM
(
select *, cnt = count(*) over (partition by ID)
from [Table]
WHERE (AttrID = 3 AND ValStr ='510')
OR (AttrID = 7 AND ValStr ='2016')
OR (AttrID = 8 AND ValStr ='05')
) AS D
WHERE cnt = 3
答案 1 :(得分:2)
另一种方式
select a.* from yourTable a join
(values (3,'510'),(7,'2016'),(8,'05')) x(a,b)
on a.attrid=x.a and a.valstr=x.b
where ID = 1771373
答案 2 :(得分:1)
SELECT *
FROM Table
WHERE ((AttrID = 3 AND ValStr ='510') OR
(AttrID = 7 AND ValStr ='2016') OR
(AttrID = 8 AND ValStr ='05')
) AND
ID = 1771373
您的查询没问题。
答案 3 :(得分:1)
如果表只有ID,ATTRID和VALSTR作为列,则条件DefID=1375552
应该抛出错误。看起来您也可能在ID条件上输入错字:
SELECT *
FROM Table
WHERE ((AttrID = 3 AND ValStr ='510') OR
(AttrID = 7 AND ValStr ='2016') OR
(AttrID = 8 AND ValStr ='05'))
AND ID = 1771373
应该可以正常工作。