Group By给了我一些关于这些子查询的粗略信息

时间:2017-03-27 21:38:41

标签: sql sql-server

以下是我的查询。我遇到了group by子句和这些子查询的问题。我会在查询下方发布所需的结果。我已经尝试将第一个子查询拆分为subquerys,但这给了我更多的问题。如果有人可以提供帮助将非常感激。即使我必须采取不同的路线来实现它。

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,
    SUM(TWin) / COUNT(PlayerID) AS TAVG,
    ROW_NUMBER() OVER (PARTITION BY PlayerID ORDER BY GamingDate desc) AS TripNumber
  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

 GROUP BY PlayerID

目前我正在接受这个,

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

想要更像这样的东西,

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

谢谢!

0 个答案:

没有答案