兩個比較特殊的SQL文實現

2021-04-06 12:41:47 字數 1800 閱讀 5784

對資料庫中的資料,我們在現實的時候經常會有一些比較特殊的要求,

例如 出報表的時候,需要把本來是3列的資料,按照不同的條數變成柳列來顯示,如果用程式來實現這樣的功能,一般都比較繁瑣,並且效率也不是很高,如果使用sql語句來完成的話,那麼資料在一出來的時候就是我們想要的格式,豈不是很好。

下面就是兩個比較特殊的實現

原始資料和表的結構如下

name

stuno

***張三

001男

李四 002 

男張艷 

003 

女王一 

004 

男王二 

005 

男王豔 

006 女

第一種實現,我們需要把一行資料變成兩行,變成張三男

這樣我們就可以在程式中用兩行或者是個多的行,來表示資料庫中的一條資料,這個方法在資料庫中資料字段比較多的時候,可以用乙個grid來顯示,實現的sql語句如下:

select stuno,name from

(select * from (select top 10000 stuno,[name],1 as [no] from tblstudent order by stuno) t

union all

select * from (select top 10000 stuno,[***] as [name],2 as [no]  from tblstudent order by stuno) t

) f

order by stuno,[no]

stuno

name

001 

張三001 

男002 

李四002 

男003 

張艷003 

女004 

王一004 

男005 

王二005 

男006 

王艷006 女

第二種實現方法,將資料變成6列來表示

select top 1 * from tblstudent a

left join (select top 1 * from tblstudent where (stuno not in (select top 2 stuno from tblstudent b))) d on 1=1

left join (select top 1 * from tblstudent where (stuno not in (select top 4 stuno from tblstudent b))) e on 1=1

union

select top 1 * from tblstudent a

left join (select top 1 * from tblstudent where (stuno not in (select top 3 stuno from tblstudent b))) d on 1=1

left join (select top 1 * from tblstudent where (stuno not in (select top 5 stuno from tblstudent b))) e on 1=1

where a.stuno not in (select top 1 stuno from tblstudent)

實現後的大致效果如下:

張三001男李四

002男

張艷003女王二

005男

這兩種方法,對於一些特殊要求的資料形式比較有用,希望可以對大家有所幫助。

實現環境:winxp sp2

sql server 2000 developer 

C 自帶實現兩個vector的比較

今天在做一道leetcode題 拼接最大數時,遇到乙個問題 就是我有兩個vector a b 我要歸併a b 使最後得到的vector個元素組成的數字最大,並保持在原陣列的相對有序 所以會存在這樣一種情況 a b a 0 和b 0 相等,我如果隨意取了a 0 那麼我下一次就拿a 1 和b 0 比,結...

比較兩段SQL文的時間

create table skk.zm test strtitle char 20 datetimenow timestamp 6 timenow number delete from zm test insert into zm test values start1 systimestamp,0 ...

兩個物件屬性的比較

兩個物件的引用比較可以用equal 但是兩個物件的屬性比較就比較麻煩一些,寫乙個方法,僅供參考 1 public static bool propertyequals object aobject1,object aobject2 2 27 28else if vobject1 is list vo...