① 執行hr_cre.sql創建7張測試表並添加測試數據。
1、創建測試表、插入數據:
create table test
(id int,
name varchar(10),
score int,
classname varchar(20));
insert into test values (1,'張三',100,'一班');
insert into test values (2,'李四',89,'一班');
insert into test values (3,'王五',97,'一班');
insert into test values (4,'趙六',87,'二班');
insert into test values (5,'孫七',94,'二班');
insert into test values (6,'楊八',76,'二班');
2、查詢每個班級的總分,可用如下語句:
select classname,SUM(score) as 總分 from test group by classname;
3、結果截圖:
② 關於sql 包中的 statement 介面
你只知道什麼是介面,卻不知道為什麼要使用介面。
聽說介面回調這個說法嗎。你必須關心statement是怎麼來的。
Statement statement=connection.creStatement();
問題就在這句話裡面。 connection.creStatement();返回的到底是什麼?
請你仔細想好再回答。
其實connection.creStatement();返回的是一個實現了statement介面的類。
當然你不知道到底是哪個類,你只要知道它實現了statement介面就行,然後用介面的引用去指向那個類就叫介面回調。 你想想,你要開燈只要按一下那個開關,相當於那個介面引用,至於那個開關具體是怎麼實現開關燈功能的你不知道,你也不需要知道,對使用者來說,這就是介面的一大好處。因為具體返回哪個類由Connection類來決定,而且恰恰那個類也不用你寫。
那麼現在你應該知道 了,statement.execute();實現了沒有。 也就是人家幫你實現了那個介面,你只管用,不用關具體怎麼實現的,因為,那個方法需要什麼參數,有什麼功能在介面里已經寫的很清楚了。
再給你一個介面回調的例子。迭代器的實現
HashSet set=new HashSet();
Iterator it=set.iterator();
由hashset來決定怎麼去實現iterator介面,你只管定義介面引用,然後就去使用介面里有的方法就行。
③ 請教sql語句
先建一個自定義函數(SQL SERVER資料庫)
create function cre_funcation(@a int)--傳入參數為A表的那個欄位
returns varchar(2000)
as
begin
declare @str varchar(2000)
set @str=''
select @str=@str+','+a.b_name from tableB a
where a.a_id=@a
if len(@str)>0
begin
set @str=right(@str,len(@str)-1)
end
else
begin
set @str='無'
end
return @str
end
再寫查詢語句
select a.*,dbo.cre_funcation(a_id) from tablea
--注意,自己改一下表名或者欄位名,這樣就一定可以的。