简体   繁体   中英

SQL PIVOT a table with no column names

I had a query returning value in a list. eg:

SELECT *
FROM some_table
WHERE name IN ('name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8', 'name9', 'name10')

I want to see what might not be in the list. eg:

SELECT *
FROM #list
WHERE name NOT IN (SELECT name FROM some_table)

My list has a few hundred values. How can I turn my list into a table?

SELECT 'name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8', 'name9', 'name10'

INTO #list UNPIVOT(?????)

create table SomeTable (  -- The reference table
    Name varchar(20));

insert SomeTable(Name)
values
     ('name1')
    ,('name2')
    ,('name3')
    ,('name4')
    ,('name5');


select T1.Name from
(values                 -- The list to compare to the reference table
     ('name1')
    ,('name2')
    ,('name129')) as T1(Name)
EXCEPT
select Name from SomeTable;

This will return "name129" since that value is in the list but not in the reference table. The same effect can be achieved with NOT EXISTS or with an outer join.

select T1.Name from
(values                 -- The list to compare to the reference table
     ('name1')
    ,('name2')
    ,('name129')) as T1(Name)
left outer join SomeTable as st
    on st.Name = T1.Name
where st.Name is NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM