[英]Query for match all records in list SQL Server
我有一张表bawe_services。 我想获取与给定键匹配的所有数据
就像我有田野
id | Service_id |bawe_id
1 2 2
2 3 3
3 2 3
如果我通过service = 2我需要通过service = id,2的所有记录,如果我通过service = 1,2,3而不是我想要0行,因为1条服务都没有得到任何授权。 我有0行。
我用这个查询
select * from aspnet_bawe_services where ser_id in(1,2,3)
提前感谢
“ in”语句中参数的数量必须与具有相等数量的数量匹配。
select bawe_id from [dbo].[aspnet_bawe_services]
where Service_id in (2)
group by bawe_id
having count(Service_id)=1;
bawe_id
-----------
2
3
select bawe_id from [dbo].[aspnet_bawe_services]
where Service_id in (2,3)
group by bawe_id
having count(Service_id)=2;
bawe_id
-----------
3
select bawe_id from [dbo].[aspnet_bawe_services]
where Service_id in (1,2,3)
group by bawe_id
having count(Service_id)=3;
bawe_id
-----------
(0 row(s) affected)
尝试一下:这确实很乏味,但要求独特,我认为要实现这一点,我们必须使用功能
1-函数返回不同的service_id计数
2个功能,用于分隔逗号分隔的值并以表格格式返回
-函数返回service_id的唯一计数
CREATE FUNCTION [dbo].[getCount](@service_id varchar(500))
RETURNS INT
AS
BEGIN
DECLARE @count int
SELECT @count = COUNT(DISTINCT(t.service_id))
FROM tmptos t
INNER JOIN [dbo].[SplitValue](@service_id, ',') tt on t.service_id = tt.items
RETURN @count
END;
-分割逗号分隔值并以表格式返回的函数-从以下位置复制的函数- 分隔逗号分隔值并存储在sql server中的表中
CREATE FUNCTION [dbo].[SplitValue](@String varchar(MAX), @Delimiter char(1))
RETURNS @temptable TABLE (items VARCHAR(MAX))
AS
BEGIN
DECLARE @idx int
DECLARE @slice varchar(8000)
SELECT @idx = 1
if len(@String)<1 or @String is null return
WHILE @idx!= 0
BEGIN
set @idx = charindex(@Delimiter,@String)
IF @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
IF(LEN(@slice)>0)
INSERT INTO @temptable(Items) values(@slice)
SET @String = right(@String,len(@String) - @idx)
IF LEN(@String) = 0 break
END
RETURN
END;
--Table with Sample Data
create table tmptos(id int, Service_id int, bawe_id int)
insert into tmptos values
(1, 2, 2),
(2, 3, 3),
(3, 2, 3)
declare @service_id varchar(50) = '2,3'
select *
from tmptos t
inner join [dbo].[SplitValue](@service_id, ',') tt on t.Service_id = tt.items
where [dbo].[getCount](@service_id) = (select count(distinct(items)) from [dbo].[SplitValue](@service_id, ','))
OUTPUT:
id Service_id bawe_id items
1 2 2 2
2 3 3 3
3 2 3 2
它有点长,但是效果很好。
select * from aspnet_bawe_services
where Service_id in (1,2,3)
and
( select count(distinct Service_id) from aspnet_bawe_services where Service_id in (1,2,3) ) = 3
查询中的最后一个数字(在本例中为“ 3”)是元素计数,该数字在IN
列表中。
您可以使用group by
并having
来获取要使用的服务ID:
select service_id
from t
where bawe_id in (1, 2, 3)
group by service_id
having count(distinct bawe_id) = 3;
“ = 3”是IN
列表中ID的数量。
然后in
您可以使用in
或join
或exists
获取完整的记录:
select t.*
from t
where t.service_id in (select service_id
from t
where bawe_id in (1, 2, 3)
group by service_id
having count(distinct bawe_id) = 3
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.