Sql server 同一select查询中不同集合的Sql分组
我有以下格式的表格Sql server 同一select查询中不同集合的Sql分组,sql-server,group-by,Sql Server,Group By,我有以下格式的表格 reporting_date interest_payment balance 200401 5 10 200401 10 20 200403 25 25 200403 15 10 200406 5 10 200
reporting_date interest_payment balance
200401 5 10
200401 10 20
200403 25 25
200403 15 10
200406 5 10
200407 20 10
200407 25 5
我想在报告日期的基础上,将不同的栏目分组,使我的输出看起来像这样
reporting_date interest_payment balance
200401 15 10
200403 40 25
200406 5 10
200407 45 10
i、 e利息支付应按报告日期分组,但在对余额分组时,我只想按该报告日期的第一行分组
因此,对于200401年,利息支付将是15,而余额将只有10
select sum(interest_payment),sum(balance)
from table
group by reporting_date
这是我计划使用的查询,但显然它对平衡列不起作用。是否有办法在sql server中处理此问题,以便在单个查询中我可以按特定集合进行分组,但对于其他查询,我可以按不同集合进行分组
谢谢。您可以使用以下查询:
with t as (
select
reporting_date,
interest_payment,
first_value(balance) over (partition by reporting_date order by reporting_date) as b
from table
)
select reporting_date, sum(interest_payment), min(b)
from t
group by reporting_date
SELECT reporting_date, balance, (SELECT SUM(interest_payment)
FROM #mytable
WHERE reporting_date = t.reporting_date
GROUP BY reporting_date) AS sum_of_interest
FROM (
SELECT reporting_date, balance,
ROW_NUMBER() OVER (PARTITION BY reporting_date ORDER BY id) AS rn
FROM #mytable ) t
WHERE t.rn = 1
我假设
id
字段定义了余额的优先级
,也就是说,具有最低相关id
值的balance
首先出现。在前两条记录中,10的balance优先于20的balance?我想在分组集合中选择第一个balance字段,首先定义什么?屏幕上的显示顺序不是sql查询可以使用的标准。因此,我有10列要聚合,其中1列需要与其他9列不同的逻辑,我会使用SELECT SUM(利息支付)吗从#mytable,其中reporting_date=t。reporting_date GROUP BY reporting_date)作为9列其余部分的利息总和显示如果我还有5个利息支付1,利息支付2….我是否修改此查询。。。。利息支付5 alnogwith balance column to group BY此查询需要对表行进行双重扫描。我的版本比较便宜,只需一次就可以执行。