连续获取MAX和MIN SQL

时间:2017-03-28 02:35:25

标签: sql sql-server

;WITH CTE AS
(
    SELECT * FROM
    (
        SELECT CandidateID, t_Candidate.Name, ISNULL(CAST(AVG(Rate) AS DECIMAL(12,2)),0) AS Rate, t_Ambassadors.Name AS CN
        FROM t_Vote INNER JOIN t_Candidate 
        ON t_Vote.CandidateID = t_Candidate.ID
        INNER JOIN t_Ambassadors 
        ON t_Vote.AmbassadorID = t_Ambassadors.ID
        GROUP BY Rate, CandidateID, t_Candidate.Name, t_Ambassadors.Name
    )MySrc
    PIVOT
    (
        AVG(Rate)
        FOR CN IN ([Jean],[Anna],[Felicia])
    )AS nSrc

)SELECT CandidateID, Name, CAST([Jean] AS DECIMAL(12,2)) AS AHH ,CAST([Anna] AS DECIMAL(12,2)) AS MK,CAST([Felicia] AS DECIMAL(12,2)) AS DIL, CAST(([Jean] + [Anna] + [Felicia])/3 AS DECIMAL(12,2)) AS Total
FROM CTE
GROUP BY Cte.CandidateID, cte.Name, cte.[Jean], cte.[Anna], cte.[Felicia]

我用上面的查询解决了我以前的问题。我创建了一个新问题,因为我遇到了新问题。如何连续获得最大和最小速率?

以下是我从上述查询得到的结果:

| CandidateID | Name |  AHH  |  MK  | DIL  | Total |
|-------------|------|-------|------|------|-------|
|     CID1    | Jay  | 7.00  | 3.00 | 3.00 | 4.33  |
|     CID2    | Mia  | 2.00  | 9.00 | 7.00 | 6.00  |

我想要实现的目标是:

| CandidateID | Name |  AHH  |  MK  | DIL  | Total |
|-------------|------|-------|------|------|-------|
|     CID1    | Jay  | 7.00  | 3.00 | 3.00 | 3.00  |
|     CID2    | Mia  | 2.00  | 9.00 | 7.00 | 7.00  |

所以在第二个结果上发生了什么,它从行中删除了最高和最低得分/率并获得剩余率/得分的平均值。 AHH,MK和DIL不是唯一的选民,其中有14个,我只是拿了3个让它变得更短更清晰。

1 个答案:

答案 0 :(得分:3)

我相信你正在寻找类似下面的东西(虽然我使用的是案例聚合而不是支点)。

基本上,它会对你的查询做同样的事情,除了它使用行号来计算最高和最低,并将它们从最终的“总数”中排除(在平局的情况下,它只会选择一个其中,如果您不想在平均值中包含最高/最低值,则可以使用RANK()代替row_number():

WITH CTE AS
(
    SELECT CandidateID,
           Name,
           CN,
           Rate,
           Lowest = ROW_NUMBER() OVER (PARTITION BY CandidateID, Name ORDER BY Rate),
           Highest = ROW_NUMBER() OVER (PARTITION BY CandidateID, Name ORDER BY Rate DESC)
    FROM
    (
        SELECT CandidateID,
               t_Candidate.Name,
               CN = t_Ambassadors.Name,
               Rate = ISNULL(CAST(AVG(Rate) AS DECIMAL(12,2)),0)
        FROM t_Vote
        JOIN t_Candidate
            ON t_Vote.CandidateID = t_Candidate.ID
        JOIN t_Ambassadors
            ON t_Vote.AmbassadorID = t_Ambassadors.ID
        GROUP BY CandidateID, t_Candidate.Name, t_Ambassadors.Name
    ) AS T
)
SELECT CandidateID,
       Name,
       AHH = MAX(CASE WHEN CN = 'Jean' THEN Rate END),
       MK = MAX(CASE WHEN CN = 'Anna' THEN Rate END),
       DIL = MAX(CASE WHEN CN = 'Felicia' THEN Rate END), -- and so on and so forth for each CN
       Total = AVG(CASE WHEN Lowest != 1 AND Highest != 1 THEN Rate END)
FROM CTE
GROUP BY CandidateID, Name;

编辑:可以使用PIVOT执行此操作,但除非我弄错了,否则在转动之前计算出不是最高和最低的平均值的问题,这变得有点复杂。使用案例聚合,IMO更容易。