两列之间的最大差异

时间:2016-02-09 07:12:08

标签: sql sql-server-2012

需要比较两个列值find并想要找出这两个列值之间的差异,并且最后想要显示该表中存在的最大差异的所有值

companyname     open    close   date
A                 10      9.8   2015-01-01
A                 11      8.2   2015-02-01 
A                9.8     6.5    2015-02-04
B                 10      8     2015-04-01
B                 9.9    9.5    2015-04-15
C                 8.7    2.3    2015-02-01

现在我想查询显示输出

company name    open    close  difference  date
A                9.8     6.5     3.3       2015-02-04
B                 10      8       2        2015-04-01
c                 8.7     2.3    6.4       2015-02-01

3 个答案:

答案 0 :(得分:3)

原始表的简单INNER JOIN到子查询,只需获得每个公司的最大差异即可。

SELECT c1.companyname, c1.open, c1.close, c2.maxTime AS difference, c1.date
FROM companies c1
INNER JOIN
(
    SELECT companyname, MAX(open - close) AS maxTime
    FROM companies
    GROUP BY companyname
) c2
ON c1.companyname = c2.companyname AND (c1.open - c1.close) = c2.maxTime

请点击以下链接查看正在运行的演示(由@lc提供):

SQLFiddle

答案 1 :(得分:1)

尝试;

select 
    [companyname],
    [open],
    [close],
    [open] - [close] diff,
    [date]
From (
    select 
        [companyname],
        [open],
        [close],
        [date],
        rank() over (partition by [companyname] order by [open] - [close] desc) rnk
    From my_table
) x
where rnk = 1

sql fiddle demo

答案 2 :(得分:1)

作为@TimBiegeleisen's answer中自联接的替代方法,您可以使用窗口函数按companyname分区的差异排序,然后从每个分区中选择第一行:

select [companyname] as [company name], [open], [close], [difference], [date]
from (
    select [companyname], [open], [close], 
        [open] - [close] as [difference], [date],
        row_number() over (partition by [companyname] 
                           order by [open] - [close] desc) rn
    from Table1
) x
where rn = 1

[SQL Fiddle demo]