从表中选择特定记录

时间:2013-05-29 04:57:50

标签: sql-server tsql

我有一个sql表如下

Desc   code1   code2   type1  type2
-------------------------------------    
desc1  123     234     T       M
desc2  444     421     T       M
desc3  491     212     T 
desc4  322     211     T
desc5  333     312     T

现在我必须每次选择前两条记录,根据某些条件从剩余的三条记录中选择一条记录,如何从这个表中首先选择三条记录,第二条和剩下的三条记录...请帮忙

2 个答案:

答案 0 :(得分:8)

SELECT TOP 2 * FROM table ORDER BY (something)
UNION ALL
SELECT TOP 1 * FROM table WHERE (something) (maybe ORDER BY something)

或者如果在前2中你的意思是type2 = M的记录那么:

SELECT TOP 2 * FROM table WHERE type2='M'
UNION ALL
SELECT TOP 1 * FROM table WHERE (something)

或者如果你想要前2名和一些随机的第三名,那么

SELECT TOP 2 * FROM table WHERE type2='M'
UNION ALL
SELECT TOP 1 * FROM table WHERE type2<>'M' ORDER BY NEWID()

答案 1 :(得分:0)


  SELECT TOP (2)* FROM TOPP
  UNION 
  SELECT TOP(1) * FROM TOPP A 
  WHERE A.DESC NOT IN (SELECT TOP((SELECT COUNT(*) FROM TOPP)-3) DESC FROM TOPP)

TableName = Topp