azuresql:基于sub select语句对结果进行分组

vsnjm48y  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(277)

我在一个查询中遇到了一个问题,在这个查询中,我希望累积值,然后将它们分组:这是一个简化的示例

CREATE TABLE [dbo].[OWNER](
    [personId] [int] NULL,
    [ownerId] [int] NULL,
    [firstName] [varchar](255) NULL,
    [lastName] [varchar](255) NULL,
)
GO

CREATE TABLE [dbo].[INCOME](
    [personId] [int] NULL,
    [amount] [float] NULL,
    [received] [date] NULL,
)
GO

INSERT INTO OWNER Values(1,null,   'John', 'Smith')
INSERT INTO OWNER Values(1,null,   'John', 'Smith')
INSERT INTO OWNER Values(1,null,   'John', 'Smith')
INSERT INTO OWNER Values(200,1,    'Tom', 'Lawn')
INSERT INTO OWNER Values(3,3,      'Chris', 'Hanson')
INSERT INTO OWNER Values(400,4,    'Jack', 'Man')
INSERT INTO OWNER Values(4,null,   'Donald', 'McMan')
INSERT INTO OWNER Values(5,null,   'John', 'Hanson')
INSERT INTO OWNER Values(700,5,    'Peter', 'Darcy')
INSERT INTO OWNER Values(700,5,    'Peter', 'Darcy')

Insert INTO INCOME VALUES(1, 300, '2020-01-01')
Insert INTO INCOME VALUES(200, 1000, '2020-01-01')
Insert INTO INCOME VALUES(3, 200, '2020-01-01')
Insert INTO INCOME VALUES(4,300, '2020-01-01')
Insert INTO INCOME VALUES(5,300, '2020-01-01')
Insert INTO INCOME VALUES(1,300,  '2020-01-01')
Insert INTO INCOME VALUES(3,300,  '2020-01-01')
Insert INTO INCOME VALUES(5,500,  '2020-01-01')
Insert INTO INCOME VALUES(700,500,  '2020-01-01')

在owner表中可以有重复的记录。做一个我能写的聚合

select personId, 
       sum(amount) as total,
       count(*) as rows
from income
group by personid

这将导致

personId    total   rows
1           600      2
3           500      2
4           300      1
5           800      2
200         1000     1
700         500      1

问题是,我想获得所有者的聚合,并得到以下结果

personId    total  rows
1           1600   3
3           500    2
4           300    1
5           1300   3

因为Personid200的ownerid是1,Personid700的ownerid是5。我将感谢您对如何实现这一目标的帮助。

a14dhokn

a14dhokn1#

您的数据模型有一个真正的问题——您应该解决这个问题。有重复行的 owner 只是不好。至少,你可以有一个生效日期,这样你就知道最近的记录是什么了
也就是说,你可以用 apply 要选择任意匹配记录并使用它,请执行以下操作:

select coalesce(o.ownerid, i.personid), 
       sum(amount) as total,
       count(*) as rows
from income i cross apply
     (select top (1) o.*
      from owner o
      where o.personid = i.personid
     ) o
group by coalesce(o.ownerid, i.personid);

这是一把小提琴。

相关问题