關於SQL查詢語句合併結果集

2021-10-08 05:00:58 字數 1602 閱讀 6375

整理別人的sql

大概的思想是用union 和union all

--合併重複行

select * from a

union

select * from b

--不合併重複行

select * from a

union all

select * from b

按某個字段排序

--合併重複行

select *

from (

select * from a

union

select * from b) as t

order by 欄位名

--不合併重複行

select *

from (

select * from a

union all

select * from b) as t

order by 欄位名

//sql server版

select * from (

select top 2 id,adddate,title,url from barticle where classid='1' order by adddate desc) a

union all

select * from (

select top 2 id,adddate,title,url from barticle where classid='2' order by adddate desc) b

union all

select * from (

select top 2 id,adddate,title,url from barticle where classid='3' order by adddate desc) c

union all

select * from (

select top 2 id,adddate,title,url from barticle where classid='4' order by adddate desc) d

//mysql版

select * from (

select id,adddate,title,url from barticle where classid='1' order by adddate desc limit 0,2) a

union all

select * from (

select id,adddate,title,url from barticle where classid='2' order by adddate desc limit 0,2) b

union all

select * from (

select id,adddate,title,url from barticle where classid='3' order by adddate desc limit 0,2) c

union all

select * from (

select id,adddate,title,url from barticle where classid='4' order by adddate desc limit 0,2) d

SQL語句裡合併兩個select查詢結果

sql union 操作符 union 操作符用於合併兩個或多個 select 語句的結果集。請注意,union 內部的 select 語句必須擁有相同數量的列。列也必須擁有相似的資料型別。同時,每條 select 語句中的列的順序必須相同。sql union 語法 select column na...

sql查詢結果集匯出Excel

t sql exec master.xp cmdshell bcp 庫名.dbo.表名out c temp.xls c q s servername u sa p 引數 s 是sql伺服器名 u是使用者 p是密碼 說明 還可以匯出文字檔案等多種格式 declare str varchar 600 s...

SQL語句查詢結果轉excel

直接輸出到servlet可以不用在硬碟上寫檔案 int rows l.size 行數 system.out.println l.size for int i 1 i 取得輸出流 outputstream out res.getoutputstream 清空輸出流 res.reset res.seth...