Re: [SQL ] 兩張資料表合成一張
※ 引述《JGC18 (JGC)》之銘言:
: 資料庫名稱:
: MS SQL Server
: 資料庫版本:
: 2008 R2
: 內容/問題描述:
: 大家好,小弟目前碰到要把兩張資料表合成一張顯示
: table_A
: 欄位有
: store_id, data, enable
: H1 xxx.. 1
: H1 yyy.. 1
: H3 zzz.. 0
: H4 xyv.. 1
: -----------------------------
: tabke_B
: store_id, store_name
: H1 ABC
: H2 DEF
: H3 GHI
: H4 JKL
: -----------------------------
: 目前想把他合成一張表(只抓出table A中 enable=1的資料)如下
: store_id store_name, count
: H1 ABC 2
: H4 JKL 1
: 我會算出coumt
: select count(*),store_id from table_A where eable=1 group by store_id
: 但要怎麼把table_B的store_name加上去呢
可以考慮以下兩種寫法:
(A) subquery
(B) join
以你的例子來說:
create table table_a (
store_id varchar(2),
data varchar(10),
enable int
)
go
insert into table_A values ('H1', 'xxx', 1)
insert into table_A values ('H1', 'yyy', 1)
insert into table_A values ('H3', 'zzz', 0)
insert into table_A values ('H4', 'xyv', 1)
go
create table table_B (
store_id varchar(2) primary key,
store_name varchar(10)
)
go
insert into table_b values ('H1', 'ABC')
insert into table_b values ('H2', 'DEF')
insert into table_b values ('H3', 'GHI')
insert into table_b values ('H4', 'JKL')
go
group by 的用法您已經會了,只要再多加一道 subquery 即可查出店名,像這樣:
select store_id,
(select store_name from table_b where store_id = a.store_id) as store_name,
count(*) as counts
from table_a a
where enable = 1
group by store_id
go
另一種寫法就是網友提到的 join:
select b.store_id, b.store_name, count(*) as counts
from table_b b join table_a a on a.store_id = b.store_id
where enable = 1
group by b.store_id, b.store_name
go
其實您在另一篇的寫法已經很接近了,只不過卡在 SQL Server 語法的規定:
寫在 select 欄位清單的項目,必須是統計對象或者是那些寫在 group by 的欄位。
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.38.87.52
※ 文章網址: http://www.ptt.cc/bbs/Database/M.1400344470.A.F15.html
推
05/19 10:35, , 1F
05/19 10:35, 1F
→
05/19 10:35, , 2F
05/19 10:35, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 3 篇):