1
我有一個表前三量與人均幾個匯款:CTE每個人
CREATE TABLE [dbo].[Transactions](
[sender] [varchar](25) NULL,
[receiver] [varchar](25) NULL,
[TranDate] [date] NULL,
[amount] [money] NULL)
我必須寫一個返回收到可以說1500美元的三筆交易帳戶列表查詢。如果有三筆(或更少)轉賬,則應列出賬戶名稱,總計1500美元。 我的查詢如下:
select d.receiver, d.Somme
from(
select a.receiver,sum(a.amount) as Somme
from (SELECT top 3 receiver,[amount]
FROM [DEV_KPIGov].[dbo].[Transactions]
where receiver='Williams'
order by [amount] DESC) a
group by a.receiver
union all
select b.receiver,sum(b.amount) as Somme
from (SELECT top 3 receiver,[amount]
FROM [DEV_KPIGov].[dbo].[Transactions]
where receiver='Taylor'
order by [amount] DESC) b
group by b.receiver
union all
select c.receiver,sum(c.amount) as Somme
from (SELECT top 3 receiver,[amount]
FROM [DEV_KPIGov].[dbo].[Transactions]
where receiver='Jhonson'
order by [amount] DESC) c
group by c.receiver) d
where d.Somme>=1500
有一個更加動態的方式來實現這一目標?我不喜歡我必須在「where」子句中列出每個接收者的名字的事實。我想知道是否可以通過CTE?我使用的是SQL Server 2012的感謝
許多感謝亞歷克斯。它的工作原理 – Denise
樂意幫忙!如果你對我的回答滿意,我會喜歡它,如果你用綠色的勾號接受它 – Alex