2014-10-04 91 views
0

我有一列[Star]Integer),可以有1或2或3隨機記錄SQL Server的條款

值我有很多記錄的表。

我如何選擇我的表100分的記錄,首先選擇它[Star]列3個值 然後選擇[Star] 2值和最終選擇[Star] 1倍的值?

+0

謝謝大家,但是我的總返回記錄應該是100, – user3404171 2014-10-05 02:09:38

回答

0

,2,然後1,但只有前100用途:

Select Top (100) * 
from your_table 
where [Star] in (1,2,3) 
Order by [Star] desc 

如果不是,請添加一些澄清/樣本數據並輸出到您的問題。

0
select top 100 * from your_table where star = 1 
union all 
select top 100 * from your_table where star = 2 
union all 
select top 100 * from your_table where star = 3 
0
SELECT TOP 100 * FROM <TABLE> WHERE [Star] = 3 
UNION ALL 
SELECT TOP 100 * FROM <TABLE> WHERE [Star] = 2 
UNION ALL 
SELECT TOP 100 * FROM <TABLE> WHERE [Star] = 1 
2

訂購NEWID()會產生隨機結果。

SELECT * 
FROM (
      SELECT TOP (100) * FROM TABLE_NAME 
      WHERE [Star] = 3 
      ORDER BY NEWID() 
    ) r3 
UNION ALL 
SELECT * 
FROM (
      SELECT TOP (100) * FROM TABLE_NAME 
      WHERE [Star] = 2 
      ORDER BY NEWID() 
    ) r2 
UNION ALL 
SELECT * 
FROM (
      SELECT TOP (100) * FROM TABLE_NAME 
      WHERE [Star] = 1 
      ORDER BY NEWID() 
    ) r3 

如果一共只有100個隨機記錄您可以根據需要調整TOP(n)的,如果你想第一個3