将ROW_NUMBER()与聚合函数一起使用

时间:2020-01-21 14:54:14

标签: sql sql-server sql-server-2008 sum window-functions

让我说我有这个查询:

SELECT id, date, amount, cancelled
FROM transactions

哪个给我以下结果:

id  date     amount   ref
1   01/2019  5.00     a
1   02/2019  10.00    b
1   06/2019  20.00    c
2   10/2019  11.00    d

如果有重复的ID,我该如何获取一个具有最新日期所有金额之和和一个所有字符串的串联字符串的ID引用字段?即:

id  date     amount   ref
1   06/2019  35.00    abc
2   10/2019  11.00    d

这里是使用最大日期获取不同ID的SQL,但我不确定如何汇总数量/参考字段

WITH data_with_date_sequence AS (
    SELECT
          id
        , date
        , amount
        , ref
        , ROW_NUMBER() OVER(PARTITION BY id ORDER BY date DESC) AS seq
    FROM dbo.SomeTable
)
SELECT
      id
    , date
    , amount
    , ref
FROM data_with_date_sequence
WHERE seq = 1;

2 个答案:

答案 0 :(得分:1)

对于此用例,我看不到需要窗口函数。请考虑以下聚合查询:

select 
    id, 
    max(date) date, 
    sum(amount) amount,
    string_agg(ref, '') within group (order by date) ref
from mytable
group by id

注意:string_agg()是在SQL Server 2017中添加的。

答案 1 :(得分:1)

public class Item : INotifyPropertyChanged { public string Title { get; set; } // TODO: Notify on change public bool VisibleSelf { get; set; } // TODO: Notify on change public bool VisibleChildOrSelf { get; set; } // TODO: Notify on change public ObservableCollection<Item> Items { get; set; } // TODO: Notify on change public void CheckVisibility(string searchText) { VisibleSelf = // Title contains SearchText. You may use RegEx with wildcards VisibleChildOrSelf = VisibleSelf; foreach (var child in Items) { child.CheckVisibility(searchText); VisibleChildOrSelf |= child.VisibleChildOrSelf; } } } public class ViewModel : INotifyPropertyChanged { public ObservableCollection<Item> Source { get; set; } // TODO: Notify on change public string SearchText { get; set; } // TODO: Notify on change private void OnSearchTextChanged() // TODO: Action should be delayed by 500 millisec { foreach (var item in Source) item.CheckVisibility(SearchText); } } <StackPanel> <TextBox Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" MinWidth="200" Margin="5"/> <TreeView ItemsSource="{Binding Source}" Margin="5"> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding Items}"> <TextBlock Text="{Binding Title}" /> </HierarchicalDataTemplate> </TreeView.ItemTemplate> <TreeView.ItemContainerStyle> <Style TargetType="Control"> <Style.Triggers> <DataTrigger Binding="{Binding VisibleChildOrSelf}" Value="false"> <Setter Property="Visibility" Value="Collapsed"/> </DataTrigger> <DataTrigger Binding="{Binding VisibleSelf}" Value="false"> <Setter Property="Foreground" Value="Gray"/> </DataTrigger> </Style.Triggers> </Style> </TreeView.ItemContainerStyle> </TreeView> <StackPanel> window function一起使用:

sum()

如果您使用的是最新版本,则可以使用STRING_AGG()

这里是demo