例:
/* 产品销售 */
if (exists (select * from master.dbo.sysdatabases where name='LeetCode'))
begin
use master
drop database LeetCode
select 1
end
go
create database LeetCode
go
use LeetCode
go
-- product
if (exists (select * from sys.objects where name='Product'))
drop table Product
go
create table Product
(
product_id int primary key, -- 主键
product_name varchar(20)
);
insert into Product values(100, 'Nokia'), (200, 'Apple'), (300, 'Samsung');
go
-- Sales
if (exists (select * from sys.objects where name='Sales'))
drop table Sales
go
create table Sales
(
sale_id int identity primary key, -- 自增主键
product_id int,
year int,
quantity int,
price int,
foreign key (product_id) references Product(product_id) -- 外键
);
insert into Sales values(100, 2008, 10, 5000), (100, 2009, 12, 5000), (200, 2011, 15, 9000);
go
-- result
select p.product_id, sum(s.quantity) as total_quantity from Product p
inner join Sales s
on p.product_id=s.product_id
group by p.product_id
-- Check
select * from Sales;
go
select * from Product;
go
exec sp_tables
go
select * from sysobjects where xtype='U'
go
select product_id, sum(quantity) as total_quantity from Sales group by product_id