『壹』 關於sql相同表分組排列組合的問題
建兩個序列,並通過一個函數調用序列(union 不支持直接使用序列),用於排序。
先用第二組所有行(3行),union all 3遍第一組第一行(left join 第二組,行數就和第二組一樣了)
在用第二組所有行(3行),union all 3遍第一組第二行(left join 第二組,行數就和第二組一樣了)
最後按照序號,組別,編號排序
/*
dropsequenceBig_Letter1;
CreatesequenceBig_Letter1
Incrementby1
Startwith65
Maxvalue999999
Minvalue1
Nocycle
nocache;
dropsequenceBig_Letter2;
CreatesequenceBig_Letter2
Incrementby1
Startwith65
Maxvalue999999
Minvalue1
Nocycle
nocache;
--獲取數列下一個值
createorreplacefunctionget_seq_next(seq_nameinvarchar2)returnnumber
is
seq_valnumber;
begin
executeimmediate'select'||seq_name||'.nextvalfromal'intoseq_val;
returnseq_val;
endget_seq_next;
*/
withtmpas(
select'1'groupid,'1'numfromal
union
select'1','2'fromal
union
select'2','1'fromal
union
select'2','2'fromal
union
select'2','3'fromal
)
selectchr(get_seq_next('Big_Letter1'))xuhao,t1.groupid,t1.num
fromtmpt1wheregroupid='2'
unionall
selectchr(get_seq_next('Big_Letter2'))xuhao,t1.groupid,t1.num
fromtmpt1,tmpt2
wheret1.groupid='1'andt1.num='1'andt2.groupid='2'
union
selectchr(get_seq_next('Big_Letter1'))xuhao,t1.groupid,t1.num
fromtmpt1wheregroupid='2'
unionall
selectchr(get_seq_next('Big_Letter2'))xuhao,t1.groupid,t1.num
fromtmpt1,tmpt2
wheret1.groupid='1'andt1.num='2'andt2.groupid='2'
orderbyxuhao,groupid,num
執行結果如下:
按照這個思路拼動態SQL吧
『貳』 sql查詢問題,一個標簽表和產品表,多對多的關系,怎麼查詢同時關聯多個標簽的產品集合
用匹配查詢,把標簽表和查品表完全匹配,產品ID和標簽ID是不是一個屬性?語句如下:
Select * From 產品表 Inner Join 標簽表 on 產品表.產品ID=標簽表.標簽ID Where 產品表.ID IS NOT NULL;
意思是把產品表和標簽表裡面ID欄位完全對應地匹配起來,放在一個表裡,這句要求你產品ID和標簽ID一樣,如果不一樣,最起碼要有點關系。比如:
表1:
ID | 欄位1
----------------------
0152401 | 0000
-------------------------
0152302 | 5555
--------------------------
表2:
ID | 欄位1
----------------------
52401 | 0000
-------------------------
52302 | 5555
--------------------------
表2.ID和表1.ID的關系就是:
right(表1.ID,5)=表2.ID
我相信你兩個表之間一定有一個欄位有關系,那就用取位函數來實現匹配吧 。
不重復出現相同的行,(要完全相同的行)就在SELECT 後面加個關鍵字
Distinct
語法:
Select Distinct 欄位 From 表名;
『叄』 sql語句 組合問題
你確定是所有組合嗎?比如你有3個值a,b,c,那麼所有組合就是3+3^2+3^3=39條記錄。這其實就是笛卡爾積啊。
selecta,bfromtestunionall--一個的
selectt1.a+t2.a,t1.b+','+t2.bfromtest05t1,testt2unionall--二個的
selectt1.a+t2.a+t3.a,t1.b+','+t2.b+','+t3.bfromtestt1,testt2,testt3--三個的
結果如下: