如何计算相同ID的行并将该值除以求和列行值

时间:2017-03-27 17:57:06

标签: sql sql-server

我在下面有这个查询,我添加了TWIN计数/ PlayerID。我收到的ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效,除非还指定了TOP,OFFSET或FOR XML。

我正在尝试通过查询来计算玩家ID的总和TWIN对于那些对齐的玩家ID,并除以玩家所拥有的行程数。 1-6为最后6次旅行的每个ID获得平均值TWIN。

这是我在不尝试在中间使用计数查询的情况下获得的。

PlayerID    TripNumber  GamingDate  TWin
   7            1        6/1/2012    0.5
   8            1        2/28/2014  2.325
   8            2        1/29/2014   1.5
   8            3        1/26/2014   2.4
   8            4        1/24/2014   1.2
   8            5        1/19/2014   5.25
   8            6        1/15/2014  10.2294 
   9            1        12/29/2016  33.84


DECLARE
@iHostID int=NULL,
@iTrips int=6

DECLARE
@vTripcount int,
@vStartDate datetime,
@vHostID int,
@vTrips int;


SELECT 
@vHostID=@iHostID,
@vTrips=@iTrips;


SELECT
  PlayerID, 
  TripNumber,
  GamingDate,
  TWin,
  TAVG
  FROM
    (
    SELECT
    PlayerID,
    GamingDate,
    TWin,
    ROW_NUMBER() OVER (PARTITION BY PlayerID ORDER BY GamingDate desc) AS TripNumber
  FROM 
 (SELECT
  PlayerID,
  GamingDate,
  TWin,
  count(*) OVER (Partition by PlayerID order by GamingDate desc)/Count(*) over (partition by TWin order by GamingDate desc) as TAVG
   From

 (
     SELECT DISTINCT 
     PlayerID,
     GamingDate,
     TWin
     FROM dbo.CDS_STATDAY sd (NOLOCK) 
     WHERE IDType='P'    
  )sd

      INNER JOIN CDS_PLAYER p ON p.Player_ID=sd.PlayerID
  WHERE
      (@vHostID IS NULL OR p.HostUser_ID=@vHostID)
    )b


WHERE
  TripNumber<=@iTrips

ORDER BY
  PlayerID,
  TripNumber,
  TAVG

1 个答案:

答案 0 :(得分:1)

您可以使用SUM和COUNT函数

获取结果
DECLARE @T TABLE (PlayerId INT, TripNumber INT, GamingDate DATE, TWin DECIMAL(18,4))
INSERT INTO @T VALUES 
(7,1,'20120106',0.5),
(8,1,'20140228',2.325),
(8,2,'20140129',1.5),
(8,3,'20140126',2.4),
(8,4,'20140124',1.2),
(8,5,'20140119',5.25),
(8,6,'20140115',10.2294),
(9,1,'20161229',33.84)

SELECT PlayerId, SUM(TWIN) / COUNT(PlayerID) AS result
FROM @T
GROUP BY PlayerId

+---------+----------+
|PlayerId |result    |
+---------+----------+
|7        |0.500000  |
|8        |3.817400  |
|9        |33.840000 |
+---------+----------+