Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Particular records from table

I have a sql table as follows

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

Now I have to select first two records every time and one from remaining three records based on some conditions, how select only three records from this table first, second and one from remaining three... please help

like image 617
9 revs Avatar asked Jan 29 '26 02:01

9 revs


1 Answers

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

OR if by top 2 you mean the records where type2=M then:

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

OR if you want the top 2 and some random third, then

SELECT TOP 2 * FROM table WHERE type2='M'
UNION ALL
SELECT TOP 1 * FROM table WHERE type2<>'M' ORDER BY NEWID()
like image 150
Robert McKee Avatar answered Jan 30 '26 22:01

Robert McKee