幾個月前面試第一次遇到這種題目
大意是每行記錄的某一列和下一行記錄的某列之和,做為乙個新列儲存到結果集中,以此類推
現在想想,竟然是如此的簡單,並且實現方式不僅一種!
--測試資料
declare
@temptable
table
(id
intprimary
keyidentity
, price
int)
insert
into
@temptable
select
3union
allselect
20union
allselect
6union
allselect
12select
*from
@temptable
--執行查詢
selecta.*
, (select
sum(price)
from
@temptable
where
id <=
a.id) totalprice
from
@temptable
a先看看結果如下
新結果集的第三列是id小於當前行id的所有price之和,
這好像跟普通的查詢沒有什麼區別,只是子查詢中查詢的物件是本身,讓人有點不太習慣,就好像遞迴一樣,
自己呼叫自己,如果下次面試遇到這種題目,一定會正確的完成,哈哈!
繼續接著寫下一種實現方式,先看**
--測試資料
declare
@temptable
table
(id
intprimary
keyidentity
, price
int)
insert
into
@temptable
select
3union
allselect
20union
allselect
6union
allselect12;
with
tt as
(selecta.*
, price
astotalprice
from
@temptable
a where
id =
1union
allselecta.*
, a.price
+t.totalprice
from
@temptable
a, tt t
where
a.id
=t.id +1
)select
*from
tt這是種比較無聊的實現方式,因為寫法沒有第一種簡單,效能也不見得有優勢,完全是為了學習with的用法!
with是sql 2005的新特性, 叫公共表示式(cte),可以在裡面遞迴實現迭代查詢效果,結果跟上圖一樣
SQL Server聚合函式和子查詢迭代求和方法
2008 09 04 11 42 本文介紹了在sql server中使用聚合函式和子查詢迭代求和的公式與方法。先看看下面的表和其中的資料 t product 圖1該錶有兩個字段 xh和price,其中xh是主索引字段,現在要得到如下的查詢結果 圖2從上面的查詢結果可以看出,totalprice字段值...
利用函式實現簡單功能
1.實現乙個函式,列印乘法口訣表,口訣表的行數和列數自己指定,輸入9,輸出9 9口訣表,輸出12,輸出12 12的乘法口訣表。include include void mul int n printf n int main 2.使用函式實現兩個數的交換。include void swap int p...
第10章 模糊查詢和聚合函式
use myschool 萬用字元 匹配0 n個任意字元 匹配單個字元 匹配區間內的值 如 13 不匹配區間內的值 模糊查詢 查詢學生表中性 張 的學生記錄 select from student where studentname like 張 select from student where ...