为下表提供具有最大销售额的客户的月度销售报告

时间:2016-11-11 11:36:01

标签: sql oracle11g

enter image description here

为具有最大销售额的客户准备月度销售报告,如下表所示

1 个答案:

答案 0 :(得分:0)

这是一个如何在“一个”查询中检索的示例:

  • 拥有最高销售额的客户的ID
  • 此客户的销售摘要

首先,带来customer_id和相应销售总结的查询如下:

@ConId int, 
@ProfileId varchar(100),
@LanguageCode char(2) = NULL,
@Description nvarchar(MAX) OUTPUT
...
...
...

DECLARE @dbName varchar(100) = NULL

SELECT 
    @dbName = [providerDatabaseName] 
FROM
    [Con] WHERE id = @ConId 

IF @dbName IS NOT NULL 
BEGIN               

    CREATE EXTERNAL DATA SOURCE ProviderDB
    WITH
    (
        TYPE=RDBMS,
        LOCATION='mydomain.database.windows.net',
        DATABASE_NAME= @dbName,
        CREDENTIAL= dbadmin
    );

    EXEC sp_execute_remote @data_source_name  = N'ProviderDB', 
    @stmt = N'EXEC sp_GetProfileDescription @ProfileId, @LanguageCode, @Description OUTPUT', 
    @params = N'@ProfileId varchar(100), @LanguageCode char(2), @Description nvarchar(MAX) OUTPUT',
    @ProfileId=@ProfileId, @LanguageCode=@LanguageCode, @Description=@Description OUTPUT;

END

对于此查询,必须将排名添加到销售摘要的降序。这将允许稍后根据其等级选择单个记录。因此,必须包装:

select customer_id, sum(sales) as sumsales from mytable group by customer_id;

现在已排名的条目可用,必须选择第一个排名的记录:

select customer_id, sumsales, rank() over (order by sumsales desc) as rnk from
    (select customer_id, sum(sales) as sumsales from mytable group by customer_id);

然而,这可能不是实现这一目标的最有效方法。

编辑:

为了避免包装层,只是为了添加排名,可以将排名列表添加到第一个内部查询中:

select customer_id, sumsales from
    (select customer_id, sumsales, rank() over (order by sumsales desc) as rnk from
        (select customer_id, sum(sales) as sumsales from mytable group by customer_id)
    )
where rnk=1;

然后,需要一个包装查询来选择第一个排名的记录:

select customer_id, sum(sales) as sumsales, rank() over (order by sum(sales) desc) as rnk
from mytable group by customer_id;

参考其他类似的相关答案here