[英]T-SQL: select * from table where column in (…) with duplicates without using union all
我在Excel中有一個數據集,我有幾千個id。 在數據庫中,我需要幾列來匹配這些ID,但有些ID在Excel列表中列出兩次(並且它們需要在那里兩次)。 我正在嘗試使用IN語句編寫查詢,但它會自動過濾重復項。 但我也想要重復項,否則我需要手動重新排列Excel和SQL結果之間的數據合並。
有沒有辦法做某事
SELECT *
FROM table
WHERE id IN (
.. list of thousands ids
)
還要在不使用UNION ALL
情況下獲取重復項,以防止向數據庫發送數千個單獨的查詢?
如果要保留重復項,則需要使用left join
。 如果排序很重要,那么您也應該包含該信息。
這是一種方法:
select t.*
from (values (1, id1), (2, id2), . . .
) ids(ordering, id) left join
table t
on t.id = ids.id
order by ids.ordering;
另一種方法是將id加載到具有標識列的臨時表中以捕獲排序:
# Create the table
create table #ids (
ordering int identity(1, 1) primary key,
id
);
# Insert the ids
insert into #ids (id)
select @id;
# Use them in the query
select t.*
from #ids ids left join
table t
on t.id = ids.id
order by ids.ordering;
如果我理解正確的話,這正是IN
工作方式......
DECLARE @tbl TABLE(value INT, content VARCHAR(100));
WITH RunningNummber AS
(
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS Nmbr
FROM sys.objects
)
INSERT INTO @tbl
SELECT Nmbr,'Content for ' + CAST(Nmbr AS VARCHAR(100))
FROM RunningNummber;
--This ...
SELECT * FROM @tbl WHERE value IN(1,3,5);
-- ... is the same as this:
SELECT * FROM @tbl WHERE value IN(1,1,1,1,3,3,5,1,3,5);
如果你想組合兩個結果集,你必須加入它們......
在我看來,我認為最好在表格中導入與千位ID列表對應的值,並應用子查詢來獲取您需要的信息。
即使您在目標表中獲得了所有ID,也可以使用T-SQL過濾以刪除重復值並避免將來出現任何問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.