简体   繁体   中英

How to count rows of same ID and divide that value by summed column row value

I have this query below, I have added in the TWIN count / PlayerID. I'm getting The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

I'm trying to get the query to count the number of players ID's sum the TWIN for those aligned player ID's and divide by the amount of trips the player has. 1-6 to get the avg TWIN for each ID of the last 6 trips.

Here is what I get without trying to use the count query in the middle.

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

You could get your result using the SUM and COUNT functions

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 |
+---------+----------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM