3

我正在尝试创建一个存储过程,该过程通过“销售”表并返回药房中最好的两个客户(花了更多钱的两个客户)。

这是一些代码:

表创建:

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

有人可以帮我找到两个顶级客户吗?

谢谢恰帕

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)
4

3 回答 3

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
于 2013-06-25T22:39:03.257 回答
3

这与顶级客户一起加入了 CTE。

WITH TIES如果您只需要 2 并且不想包含与相同支出相关的客户,请删除该选项。

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 
于 2013-06-25T22:37:16.897 回答
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
于 2013-06-25T22:38:53.597 回答