chi*_*apa 3 sql sql-server stored-procedures
我正在尝试创建一个存储过程,该过程通过"SALES"表并返回药房中最好的两个客户(两个花费更多钱的客户).
这是一些代码:
表创建:
create table Customer (
Id_customer int identity(1,1) Primary Key,
Name varchar(30),
Address varchar(30),
DOB datetime,
ID_number int not null check (ID_number > 0),
Contributor int not null check (Contributor > 0),
Customer_number int not null check (Customer_number > 0)
)
create table Sale (
Id_sale int identity(1,1) Primary Key,
Id_customer int not null references Customer(Id_customer),
Sale_date datetime,
total_without_tax money,
total_with_tax money
)
Run Code Online (Sandbox Code Playgroud)
好吧,我不知道这是否有用,但我有一个功能,只要我提供客户的ID,就会返回客户花费的总金额.
这里是:
CREATE FUNCTION [dbo].[fGetTotalSpent]
(
@Id_customer int
)
RETURNS money
AS
BEGIN
declare @total money
set @total = (select sum(total_with_tax) as 'Total Spent' from Sale where Id_customer=@Id_customer)
return @total
END
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我获得两个顶级客户吗?
谢谢Chiapa
PS:这里有一些要插入的数据,所以你可以更好地测试它:
insert into customer values ('Jack', 'Big street', '1975.02.01', 123456789, 123456789, 2234567891)
insert into customer values ('Jim', 'Little street', '1985.02.01', 223456789, 223456789, 2234567891)
insert into customer values ('John', 'Large street', '1977.02.01', 323456789, 323456789, 3234567891)
insert into customer values ('Jenny', 'Huge street', '1979.02.01', 423456789, 423456789, 4234567891)
insert into sale values (1, '2013.04.30', null, 20)
insert into sale values (2, '2013.05.22', null, 10)
insert into sale values (3, '2013.03.29', null, 30)
insert into sale values (1, '2013.05.19', null, 34)
insert into sale values (1, '2013.06.04', null, 21)
insert into sale values (2, '2013.06.01', null, 10)
insert into sale values (2, '2013.05.08', null, 26)
Run Code Online (Sandbox Code Playgroud)
您可以使用单个查询执行此操作,而无需任何特殊功能:
select top 2 c.id_customer, c.name, sum(s.total_with_tax)
from customer c
join sale s on c.id_customer = s.id_customer
group by c.id_customer, c.name
order by sum(s.total_with_tax) desc
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1293 次 |
| 最近记录: |