我該給一去,應該對所有SQL implemtations工作,但我已經在T-SQL做過:
有了這些數據
declare @Category table (cat_id int, cat_description varchar(20), cat_pid int)
declare @Customer table (cust_id int, cust_name varchar(20))
declare @Customer_Has_Category table (chc_cust_id int, chc_cat_id int)
insert into @Category (cat_id, cat_description, cat_pid) values (1,'State',0)
insert into @Category (cat_id, cat_description, cat_pid) values (2,'Texas',1)
insert into @Category (cat_id, cat_description, cat_pid) values (3,'California',1)
insert into @Category (cat_id, cat_description, cat_pid) values (4,'Title',0)
insert into @Category (cat_id, cat_description, cat_pid) values (5,'Engineer',4)
insert into @Category (cat_id, cat_description, cat_pid) values (6,'Lawyer',4)
insert into @Category (cat_id, cat_description, cat_pid) values (7,'Farmer',4)
insert into @Category (cat_id, cat_description, cat_pid) values (8,'Credit Card',0)
insert into @Category (cat_id, cat_description, cat_pid) values (9,'Visa',8)
insert into @Category (cat_id, cat_description, cat_pid) values (10,'Master Card',8)
insert into @Customer (cust_id, cust_name) values (111111, 'John')
insert into @Customer (cust_id, cust_name) values (222222, 'David')
insert into @Customer (cust_id, cust_name) values (333333, 'Chris')
insert into @Customer (cust_id, cust_name) values (444444, 'Mark')
insert into @Customer_Has_Category (chc_cust_id, chc_cat_id) values (111111, 2)
insert into @Customer_Has_Category (chc_cust_id, chc_cat_id) values (111111, 5)
insert into @Customer_Has_Category (chc_cust_id, chc_cat_id) values (111111, 9)
insert into @Customer_Has_Category (chc_cust_id, chc_cat_id) values (222222, 7)
insert into @Customer_Has_Category (chc_cust_id, chc_cat_id) values (222222, 3)
insert into @Customer_Has_Category (chc_cust_id, chc_cat_id) values (333333, 6)
這個查詢
select cust_name, MAX(State) as State, MAX(Title) as Title, MAX(CreditCard) as CreditCard
from
(
select
c.cust_name,
(case when cat.cat_pid = 1 then cat_description else '' end) as State,
(case when cat.cat_pid = 4 then cat_description else '' end) as Title,
(case when cat.cat_pid = 8 then cat_description else '' end) as CreditCard
from @Customer c
left outer join @Customer_Has_Category chc on c.cust_id = chc.chc_cust_id
left outer join @Category cat on chc.chc_cat_id = cat.cat_id
) as subq
group by cust_name
給出
cust_name State Title CreditCard
-------------------- -------------------- -------------------- --------------------
Chris Lawyer
David California Farmer
John Texas Engineer Visa
Mark
如果你想取出狀態,只需從select語句中刪除它。
哪個RDBMS是這樣的?某些解決方案不適用於所有平臺。 –