仅当所有动态参数值匹配时才从表中选择

时间:2018-05-09 22:47:52

标签: sql-server tsql

我有以下animal表:

id      | action
------------------
duck    | cuack
duck    | fly
duck    | swim    
pelican | fly
pelican | swim

我想创建一个存储过程并将一组值传递给一个参数:

EXEC GuessAnimalName 'cuack,fly,swim'

Result:
duck

所以,如果它被诅咒,它飞起来它游泳然后它是一只鸭子。但是:

EXEC GuessAnimalName 'fly,swim'

Result:
pelican

---

EXEC GuessAnimalName 'fly'

Result:
No results

参数的编号是动态的。

为了猜测动物的名字,所有提供的动作必须匹配或在animal表格中找到。

这是我到目前为止所做的:

DECLARE @animal AS TABLE
(
    [id] nvarchar(8),
    [action] nvarchar(16)
)

INSERT INTO @animal VALUES('duck','cuack')
INSERT INTO @animal VALUES('duck','fly')
INSERT INTO @animal VALUES('duck','swim')
INSERT INTO @animal VALUES('pelican','fly')
INSERT INTO @animal VALUES('pelican','swim')

-- Parameter simulation
DECLARE @params AS TABLE
(
    [action] nvarchar(16)
)

INSERT INTO @params VALUES('cuack')
INSERT INTO @params VALUES('fly')
INSERT INTO @params VALUES('swim')

SELECT
    a.[id]
FROM
    @animal a
INNER JOIN
    @params p
ON
    a.[action] = p.[action]
GROUP BY
    a.[id]
HAVING COUNT(a.[action]) IN (SELECT COUNT([action]) FROM @animal GROUP BY [id])

结果如下:

Result:
--------
duck
--------
pelican

它应该只返回duck

1 个答案:

答案 0 :(得分:1)

使用RANK

将其转换为存储过程
declare @lookfor varchar(100) = 'swim,fly'

select id from 
(select 
id, rank() over (order by cnt desc)  rank_   -- get rank based on the number of match where should be the same number of rows
from
(
SELECT
    a.id, count(1) cnt   -- identify how many matches
FROM
    @animal a
INNER JOIN
    @params p
ON
    a.[action] = p.[action]
where charindex(p.action,@lookfor) > 0
group by a.id
having count(1) = (select count(1) from @animal x where a.id = x.id))  -- only get the animal with the same number of matches and rows
y)
z where rank_  = 1   -- display only with the most matches which should be the same number of rows matched

你不需要@params

select id from 
(select 
id, rank() over (order by cnt desc)  rank_
from
(
SELECT
    a.id, count(1) cnt 
FROM
    @animal a
where charindex(a.action,@lookfor) > 0
group by a.id
having count(1) = (select count(1) from @animal x where a.id = x.id))
y)
z where rank_  = 1