How can I select from list of values in SQL Server

后端 未结 14 1731
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 18:08

I have very simple problem that I can\'t solve. I need to do something like this:

select distinct * from (1, 1, 1, 2, 5, 1, 6).

Anybody can

相关标签:
14条回答
  • 2020-11-28 18:28

    Available only on SQL Server 2008 and over is row-constructor in this form:
    You could use

    SELECT DISTINCT * FROM (VALUES (1), (1), (1), (2), (5), (1), (6)) AS X(a)
    

    Many wrote about, among them:

    • [MS official] https://docs.microsoft.com/en-us/sql/t-sql/queries/table-value-constructor-transact-sql
    • http://www.sql-server-helper.com/sql-server-2008/row-value-constructor-as-derived-table.aspx
    0 讨论(0)
  • 2020-11-28 18:30

    Another way that you can use is a query like this:

    SELECT DISTINCT
        LTRIM(m.n.value('.[1]','varchar(8000)')) as columnName
    FROM 
        (SELECT CAST('<XMLRoot><RowData>' + REPLACE(t.val,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
         FROM (SELECT '1, 1, 1, 2, 5, 1, 6') AS t(val)
        ) dt
      CROSS APPLY 
        x.nodes('/XMLRoot/RowData') m(n);
    
    0 讨论(0)
  • 2020-11-28 18:31

    This works on SQL Server 2005 and if there is maximal number:

    SELECT * 
    FROM
      (SELECT ROW_NUMBER() OVER(ORDER BY a.id) NUMBER
      FROM syscomments a
      CROSS JOIN syscomments b) c
    WHERE c.NUMBER IN (1,4,6,7,9)
    
    0 讨论(0)
  • 2020-11-28 18:32

    Select user id from list of user id:

    SELECT * FROM my_table WHERE user_id IN (1,3,5,7,9,4);
    
    0 讨论(0)
  • 2020-11-28 18:32

    If it is a list of parameters from existing SQL table, for example ID list from existing Table1, then you can try this:

    select distinct ID
          FROM Table1
          where 
          ID in (1, 1, 1, 2, 5, 1, 6)
    ORDER BY ID;
    

    Or, if you need List of parameters as a SQL Table constant(variable), try this:

    WITH Id_list AS (
         select ID
          FROM Table1
          where 
          ID in (1, 1, 1, 2, 5, 1, 6)
    )
    SELECT distinct * FROM Id_list
    ORDER BY ID;
    
    0 讨论(0)
  • 2020-11-28 18:37

    A technique that has worked for me is to query a table that you know has a large amount of records in it, including just the Row_Number field in your result

    Select Top 10000 Row_Number() OVER (Order by fieldintable) As 'recnum' From largetable
    

    will return a result set of 10000 records from 1 to 10000, use this within another query to give you the desired results

    0 讨论(0)
提交回复
热议问题