从组中返回所需年份的最大值

时间:2014-03-13 17:59:31

标签: sql sql-server sql-server-2008 date

我整个下午都在这里查看了一些类似的查询,但是无法正确查询。

我正在尝试返回与所需年份的唯一ID的一组结果中的最大值相关联的标签。这是代码+输出:

select 
    fs_perm_sec_id, YEAR(date) as [Date by Year], label, sales 
from 
    ff_v2.ff_segreg_af
where 
    fs_perm_sec_id = 'SN9W4D-S-US'
    and YEAR(date) = '2013'

示例数据:

fs_perm_sec_id  Date by Year    label   sales
SN9W4D-S-US 2013    Japan   26592.96196
SN9W4D-S-US 2013    Europe  16445.23016
SN9W4D-S-US 2013    United States   12851.71355
SN9W4D-S-US 2013    Other Countries 10855.52867
SN9W4D-S-US 2013    Asia Pacific    9730.89435
SN9W4D-S-US 2013    China   5609.94288

所以在这种情况下,我想返回fs_perm_sec_id,[Date by Year]和Label - (不需要销售值)。因此,我想返回

SN9W4D-S-US | 2013 | Japan ...as my output

请记住,原始表有多个fs_perm_sec_id和日期条目。因此,最终我想强调标签与年度为2013年的所有独特条目的最大销售价值相匹配。

以下是表格中所有字段的示例:

fs_perm_sec_id  date    ff_segment_type ff_segment_num  adjdate currency    label   sales   opinc   assets  capex   dep
SN9W4D-S-US 2012-03-31  REG 1   2000-05-25  USD Japan   26729.2963  NULL    8500.71105  NULL    NULL
SN9W4D-S-US 2012-03-31  REG 2   2000-05-25  USD Europe  16106.8766  NULL    670.5828    NULL    NULL
SN9W4D-S-US 2012-03-31  REG 3   2000-05-25  USD United States   15390.4823  NULL    1007.4051   NULL    NULL
SN9W4D-S-US 2012-03-31  REG 4   2000-05-25  USD Other Countries 9865.9442   NULL    204.08355   NULL    NULL
SN9W4D-S-US 2012-03-31  REG 5   2000-05-25  USD Asia Pacific    8083.4103   NULL    450.279 NULL    NULL
SN9W4D-S-US 2012-03-31  REG 6   2000-05-25  USD China   6287.7827   NULL    478.5642    NULL    NULL
SN9W4D-S-US 2013-03-31  REG 1   2000-05-25  USD Japan   26592.96196 NULL    6571.06184  NULL    NULL
SN9W4D-S-US 2013-03-31  REG 2   2000-05-25  USD Europe  16445.23016 NULL    568.8144    NULL    NULL
SN9W4D-S-US 2013-03-31  REG 3   2000-05-25  USD United States   12851.71355 NULL    791.17976   NULL    NULL
SN9W4D-S-US 2013-03-31  REG 4   2000-05-25  USD Other Countries 10855.52867 NULL    196.66976   NULL    NULL
SN9W4D-S-US 2013-03-31  REG 5   2000-05-25  USD Asia Pacific    9730.89435  NULL    521.11528   NULL    NULL
SN9W4D-S-US 2013-03-31  REG 6   2000-05-25  USD China   5609.94288  NULL    518.05096   NULL    NULL

非常感谢v.much提前。

2 个答案:

答案 0 :(得分:0)

试试这个

select fs_perm_sec_id, [Date by Year], label
from
(
select 
    fs_perm_sec_id, YEAR(date) as [Date by Year], label, DENSE_RANK ( ) OVER (order by sales desc) as RankNo
from 
    ff_v2.ff_segreg_af
where 
    fs_perm_sec_id = 'SN9W4D-S-US'
and YEAR(date) = '2013'
) r
where RankNo = 1

答案 1 :(得分:0)

最终代码是:

use FDS3
select fs_perm_sec_id, [Date by Year], label
from
(select fs_perm_sec_id, YEAR(date) as [Date by Year], label, DENSE_RANK ( ) 
OVER (partition by fs_perm_sec_id order by sales) as RankNo
from ff_v2.ff_segreg_af where 
fs_perm_sec_id in 
('SN9W4D-S-US',
'HSDCT7-S-US',
'WHQNFK-S-US',
'PRM2JP-S-US',
'R2KQ06-S-US',
'L7GJB9-S-US',
'P47Z0J-S-US')
and YEAR(date) = '2013'
) r
where RankNo = 1
相关问题