按日期和客户选择最大收入

时间:2018-03-01 16:27:04

标签: sql sql-server tsql

以下是我桌子上的示例数据:

Rev       Date          Client
1890      2015-11-20    xyz
1536.28   2017-10-27    AAA
934.84    2017-10-27    AAA
919.592   2017-03-22    AAA 
760.985   2014-11-25    xyz

我需要为每个客户选择收入最高的那一天。

我有以下查询,但它会按客户选择每天的最高收入,而不仅仅是每个客户的每次转化率最高的那一天

SELECT TOP 1 max(rev)/1000 AS Rev, date, client FROM table1 GROUP BY date, client

5 个答案:

答案 0 :(得分:1)

常见问题。我认为Rev已经累计每天,我们只是挑选出最高排。如果存在联系,则可以使用dense_rank()代替。

select * from (
    select *, row_number() over (partition by Client order by Rev desc) as rn
    from table1
) t
where rn = 1;

答案 1 :(得分:0)

一种选择是使用 WITH TIES 子句与 Row_Number()

一起使用

示例

Select top 1 with ties *
 From  YourTable
 Order By Row_Number() over (Partition By Client Order By Rev Desc)

答案 2 :(得分:0)

设定:

DECLARE @data TABLE
(
    Rev money
    , [Date] date
    , Client nvarchar(10)
)

INSERT INTO @data
VALUES
    (1890, '2015-11-20', 'xyz')
    ,(1536.28, '2017-10-27', 'AAA')
    ,(934.84, '2017-10-27', 'AAA')
    ,(919.592, '2017-03-22', 'AAA') 
    ,(760.985, '2014-11-25', 'xyz')

查询:

SELECT Client
    , t.[Date]
FROM
(
    SELECT Client
        , [Date]
        , SUM(Rev) AS [TotalRev]
        , ROW_NUMBER() OVER (PARTITION BY Client ORDER BY SUM(Rev) DESC) AS RN
    FROM @data
    GROUP BY Client, [Date]
) AS t
WHERE t.RN = 1

结果:

Client    Date
====================
AAA       2017-10-27
xyz       2015-11-20

答案 3 :(得分:0)

我的理解michaelg的问题是每天收入最高的交易,所以:

 select * from (
    select *, row_number() over (partition by [date] order by Rev desc) as rn
    from ##table1
) t
where rn = 1;

如果您想要客户的总金额,则可以将所有内容分组到子查询中。

请在我的T-SQL代码操场https://sqleditor.net/q/B19r72H_f

中试用您的脚本

答案 4 :(得分:-1)

我会使用CROSS APPLY

SELECT DISTINCT ca.*
FROM table1 t
CROSS APPLY (SELECT TOP 1 *
             FROM table1
             WHERE Client = t.Client
             ORDER BY Rev DESC) ca

如果您已经有一个具有唯一ID的Client表,那就更干净了。

SELECT ca.Rev, ca.Date, c.Client
FROM Client c
CROSS APPLY (SELECT TOP 1 Rev, Date
             FROM table1
             WHERE Client = c.Client
             ORDER BY Rev DESC) ca