繁体   English   中英

SQL查询从多个列获取多个最大值

[英]SQL Query To Get Multiple Max Values From Multiple Columns

我试图弄清楚如何从多列中提取多个最大值。 以下是一些示例数据:

DATE | A | B | C

4/4/2011 | 64.4 | 62.1 | 33.3

4/5/2011 | 34.6 | 33.5 | 32.3

4/6/2011 | 33.1 | 49.4 | 32.1

4/7/2011 | 55.2 | 32.8 | 33.5

4/8/2011 | 31.2 | 50.1 | 30.4

4/9/2011 | 31.7 | 31.1 | 30.4

我想要前5名:

4/4/2011 | 64.4

4/4/2011 | 62.1

4/7/2011 | 55.2

4/8/2011 | 50.1

4/6/2011 | 49.4

谢谢

怎么样:

SELECT TOP 5 Date, Val 
FROM (SELECT Date, A as Val FROM T
      UNION ALL
      SELECT Date, B FROM T
      UNION ALL
      SELECT DATE, C FROM T
) AS x
ORDER BY x.Val DESC

您可以使用UNPIVOT然后按列值排序,然后只选择前5名。

像这样......


CREATE TABLE #Data 
(
    [Date] DATE,
    A  FLOAT,
    B  FLOAT,
    C  FLOAT
)

INSERT INTO 
    #Data
SELECT '4/4/2011' AS Date, '64.4' AS A, '62.1' AS B, '33.3' AS C
UNION SELECT '4/5/2011' AS Date, '34.6' AS A, '33.5' AS B, '32.3' AS C
UNION SELECT '4/6/2011' AS Date, '33.1' AS A, '49.4' AS B, '32.1' AS C
UNION SELECT '4/7/2011' AS Date, '55.2' AS A, '32.8' AS B, '33.5' AS C
UNION SELECT '4/8/2011' AS Date, '31.2' AS A, '50.1' AS B, '30.4' AS C
UNION SELECT '4/9/2011' AS Date, '31.7' AS A, '31.1' AS B, '30.4' AS C

SELECT * FROM #Data

SELECT TOP 5
    [Date],
    [Type],
    [Value]
FROM
(
    SELECT  
        [Date],
        [A],
        [B],
        [C]
    FROM
        #Data 
)pvt
UNPIVOT
(
    [Value] FOR [Type] IN
    ( [A],[B],[C])
)AS unpvt
ORDER BY
    [Value] DESC

DROP TABLE #Data

你没有告诉我们的一件事是你想要独特的结果还是允许重复。

GilM的答案将允许重复,因为他使用UNION ALL。

UNION将返回独特的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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