返回IN(1,2,3,3,3,1)子句在IN条件下具有重复项的全部

时间:2016-04-11 19:01:12

标签: sql sql-server duplicates

我需要返回以下所有值:select ... where IN(1,2,3,3,1,1)

我有一张包含唯一ID的表格。我有以下查询:

Select * From Table_1 Where ID IN (1,2,3,3,3,1);

到目前为止,我只返回3条唯一值(1,2,3)的记录

我想要返回6条记录。

我需要在图片上显示结果集。

enter image description here

3 个答案:

答案 0 :(得分:1)

您无法使用IN运算符执行此操作。您可以创建一个临时表并加入:

CREATE TABLE #TempIDs
(
ID int
)

INSERT INTO #TempIDs (1)
INSERT INTO #TempIDs (2)
INSERT INTO #TempIDs (3)
INSERT INTO #TempIDs (3)
INSERT INTO #TempIDs (3)
INSERT INTO #TempIDs (1)

Select Table_1.* From Table_1
INNER JOIN #TempIDs t n Table_1.ID = t.ID;

另一个(可能更丑陋)的选择是做UNION

Select * From Table_1 Where ID = 1
UNION ALL
Select * From Table_1 Where ID = 2
UNION ALL
Select * From Table_1 Where ID = 3
UNION ALL
Select * From Table_1 Where ID = 3
UNION ALL
Select * From Table_1 Where ID = 3
UNION ALL
Select * From Table_1 Where ID = 1

答案 1 :(得分:0)

您无法使用IN条件执行此操作,因为IN会将您的商品视为一组(即确保唯一性)。

您可以通过加入UNION ALL来生成所需的结果,如下所示:

SELECT t.*
FROM Table_1 t
JOIN ( -- This is your "IN" list
          SELECT 1 AS ID
UNION ALL SELECT 2 AS ID
UNION ALL SELECT 3 AS ID
UNION ALL SELECT 3 AS ID
UNION ALL SELECT 3 AS ID
UNION ALL SELECT 1 AS ID
) x ON x.ID = t.ID

答案 2 :(得分:0)

你可以做到。但不是IN。

Select 
src.* 
From Table_1 src
inner join (
 select
ID,
myorder
from (values
 (1,0),
(2,1),
(3,2),
(3,3),
(3,4),
(1,5)
) x (ID,myorder)
) T ON
T.ID = src.ID
order by T.myorder

请记住,如果您需要数据集,请订购,您必须提供order by子句。