Kev*_*vin 2 sql-server sql-server-2012
我在我的 sql server 2012 数据库上运行以下查询。
select Appointment.AppointmentDate, Appointment.AppointmentTime, Auctioneer.AuctioneerName, Auctioneer.AuctioneerSurname, Buyer.BuyerName, Buyer.BuyerSurname
from Appointment
inner join Auctioneer on Appointment.AuctioneerId=Auctioneer.AuctioneerId
inner join Buyer on Appointment.BuyerId=Buyer.BuyerId
where AppointmentDate between '2017-01-01' and '2017-12-31'
Run Code Online (Sandbox Code Playgroud)
结果如下:
+-----------------+-----------------+----------------+-------------------+-----------+----------------+
| AppointmentDate | AppointmentTime | AuctioneerName | AuctioneerSurname | BuyerName | BuyerSurname |
+-----------------+-----------------+----------------+-------------------+-----------+----------------+
| 2017-10-23 | 13:00:00 | Mary | Borg | David | Borg |
| 2017-10-24 | 15:30:00 | Mary | Borg | Joseph | Sammut |
| 2017-11-03 | 09:30:00 | Joseph | Smith | Mark | Psaila |
| 2017-11-03 | 10:45:00 | Joseph | Smith | David | Borg |
| 2017-11-15 | 10:10:00 | Mary | Borg | David | Borg |
| 2017-08-02 | 08:30:00 | Daisy | Webb | Josephine | Grima |
| 2017-04-15 | 14:00:00 | Sam | King | Mary | Santucci |
+-----------------+-----------------+----------------+-------------------+-----------+----------------+
Run Code Online (Sandbox Code Playgroud)
我需要添加一个列来计算结果中“AuctioneerName”和“AuctioneeSurname”的出现次数。
示例:玛丽·博格 3 次,约瑟夫·史密斯 2 次等……
我认为你只需要一个窗口count():
COUNT(*) OVER (PARTITION BY AuctioneerSurname, AuctioneerName)
Run Code Online (Sandbox Code Playgroud)
添加计算的查询 - 并为长表名使用别名:
select
app.AppointmentDate, app.AppointmentTime,
auc.AuctioneerName, auc.AuctioneerSurname,
buy.BuyerName, buy.BuyerSurname,
AuctioneerCount = count(*) over
(partition by auc.AuctioneerSurname, auc.AuctioneerName)
from
Appointment as app
inner join Auctioneer as auc
on app.AuctioneerId = auc.AuctioneerId
inner join Buyer as buy
on app.BuyerId = buy.BuyerId
where
app.AppointmentDate between '2017-01-01' and '2017-12-31' ;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1764 次 |
| 最近记录: |