简体   繁体   中英

How to combine multiple SQL queries

I am new to SQL and I am trying to figure out how to get multiple queries into the same result of six items.

The queries I want to combine are:

SELECT TOP 2 * 
FROM tablename 
WHERE (time >= '20180226 21:00' AND channelname = 'A') 
ORDER BY time ASC 

SELECT TOP 2 * 
FROM tablename 
WHERE (time >= '20180226 21:00' AND channelname = 'B') 
ORDER BY time ASC 

SELECT TOP 2 * 
FROM tablename 
WHERE (time >= '20180226 21:00' AND channelname = 'C') 
ORDER BY time ASC 

The only thing that changes is the ChannelName , and I'm sure there is a way to do this but my syntax skills around SQL are to say the least, limited, I'm stuck.

Select * from (SELECT TOP 2 * 
FROM   tablename 
WHERE ( time >= '20180226 21:00' 
        AND channelname = 'A' ) ORDER  BY time ASC )t1
UNION ALL 

Select * from (SELECT TOP 2 * 
FROM   tablename 
WHERE ( time >= '20180226 21:00' 
        AND channelname = 'B' ) ORDER  BY time ASC )t2
UNION ALL

Select * from (SELECT TOP 2 * 
FROM   tablename 
WHERE ( time >= '20180226 21:00' 
        AND channelname = 'C' ) 
ORDER  BY time ASC )t3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM