根据具体值进行选择

时间:2016-04-24 22:23:28

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我有这张桌子:

     ID     NO.
     111    6
     222    7
     333    9
     111    8
     333    4
     222    3
     111    7
     222    5
     333    2

我想从表中只选择2个ID号,否则。列等于特定值。 例如,我尝试了这个查询,但我没有得到预期的结果:

SELECT top 2 * FROM mytable where NO. in 
(select NO. from mytable )

预期结果:

    111    6
    111    8
    222    7
    222    3
    333    9

333 3

3 个答案:

答案 0 :(得分:2)

我猜(333,3)是一个错误,你期望(333,2)。如果不是,我不知道。

SELECT
    ua.ID
  , ua.[NO.]
FROM (
SELECT 
    ROW_NUMBER() OVER (PARTITION BY ID ORDER BY t.[NO.] ASC) AS RowNum
  , t.ID
  , t.[NO.]
FROM dbo.t1 AS t
UNION ALL
SELECT 
    ROW_NUMBER() OVER (PARTITION BY ID ORDER BY t.[NO.] DESC)
  , ID
  , t.[NO.]
FROM dbo.t1 AS t
) ua
WHERE ua.RowNum = 1
ORDER BY ID, ua.[NO.] DESC

如果您只是想为每个组获取前2个值,则需要定义顺序,即。第三栏。然后你不需要UNION ALL,只需使用WHERE ua.RowNum< 3。

答案 1 :(得分:2)

您似乎想根据No列上的条件为每个ID在表格中选择两行。为此,一种方法使用row_number()

select t.*
from (select t.*, row_number() over (partition by id order by id) as seqnum
      from mytable t
      where <condition goes here>
     ) t
where seqnum <= 2;

答案 2 :(得分:0)

/*Select 2 random rows per id where the number of rows per id can vary between 1 and infinity
A good article for this:-*/
--https://www.mssqltips.com/sqlservertip/3157/different-ways-to-get-random-data-for-sql-server-data-sampling/

DECLARE @TABLE TABLE(ID INT,NO INT)
INSERT INTO @TABLE
VALUES
(111,    6),
(222,    7),
(333 ,   9),
(111  ,  8),
(333   , 4),
(222   , 3),
(111   , 7),
(222   , 5),
(333   , 2)

select t.* from 
(
Select s.* ,ROW_NUMBER() OVER(PARTITION BY ID ORDER BY randomnumber) ROWNUMBER
from
(
 SELECT ID,NO, 
 (ABS(CHECKSUM(NEWID())) % 100001) + ((ABS(CHECKSUM(NEWID())) % 100001) * 0.00001) [randomnumber]
 FROM   @TABLE
) s 
) t
where t.rownumber < 3