SQL存储过程以获取顶级客户

时间:2013-06-25 22:30:32

标签: 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
    )

好吧,我不知道这是否有用,但我有一个功能,只要我提供客户的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

有人可以帮助我获得两位顶级客户吗?

由于 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)

3 个答案:

答案 0 :(得分:5)

您可以使用单个查询执行此操作,而无需任何特殊功能:

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

答案 1 :(得分:3)

这与顶级客户加入CTE。

如果您只想要2,请删除WITH TIES选项,并且不希望包含使用相同花费的客户。

WITH Top2
     AS (SELECT TOP 2 WITH TIES Id_customer,
                                SUM(total_with_tax) AS total_with_tax
         FROM   Sale
         GROUP  BY Id_customer
         ORDER  BY SUM(total_with_tax) DESC)
SELECT *
FROM   Customer C
       JOIN Top2 T
         ON C.Id_customer = T.Id_customer 

答案 2 :(得分:2)

我不是真正使用SQL Server方言,但是这个方法会按照降序排列给你最好的客户以及他们花的钱:

select Id_customer, total_with_tax from
(select Id_customer, sum(total_with_tax) total_with_tax from Sale group by Id_customer)
order by total_with_tax desc