SQL Server:如何获得最大列数

时间:2014-07-23 01:42:38

标签: sql-server max

在SQL Server中,请告诉我如何获取最多列。

数据:

 QRY_ID  |  SUBJECT1  |  SUBJECT2 | ..........................  SUBJECT20
------------------------------------------------------------------------------
   A     |    100     |    15     | ..........................     120   
   B     |    200     |    32     | ..........................     140  
   C     |    32      |    29     | ..........................     230  
   D     |    78      |    61     | ..........................     420  
   E     |    99      |    30     | ..........................     20  

期望的结果:

 QRY_ID  |  MAX(SUBJECT) | 
--------------------------
   A     |    120    |  
   B     |    200    |  
   C     |    230    |     
   D     |    420    |      
   E     |    99     |   

谢谢〜!

2 个答案:

答案 0 :(得分:3)

如果您使用的是支持UNPIVOT的SQL Server版本,可以尝试:

SELECT      QRY_ID, MAX([VALUE]) AS [MAX(SUBJECT)]
FROM        MyTable
UNPIVOT
(
    [VALUE]
    FOR SUBJECT IN (SUBJECT1, SUBJECT2,...SUBJECTX)
) up
GROUP BY    QRY_ID;

否则:

SELECT      QRY_ID, MAX(SUBJECT) AS [MAX(SUBJECT)]
FROM
(
    SELECT QRY_ID, SUBJECT1 AS SUBJECT FROM MyTable
    UNION ALL
    SELECT QRY_ID, SUBJECT2 AS SUBJECT FROM MyTable
    UNION ALL
    ...
    SELECT QRY_ID, SUBJECTX AS SUBJECT FROM MyTable
) t
GROUP BY    QRY_ID;

答案 1 :(得分:1)

试试这个:

SELECT qry_id,MAX(subject1) FROM t GROUP BY qry_id

SqlFiddle(http://sqlfiddle.com/#!3/69643/2)架构和示例数据:

CREATE TABLE t 
    (
     qry_id varchar(1), 
     subject1 int
    );

INSERT INTO t
(qry_id, subject1)
VALUES
('A', 99),
('A', 100),
('E', 200),
('E', 40),
('D', 23),
('X', 60),
('B', 10);

结果:

QRY_ID  MAX_SUBJECT1
A       100
B       10
D       23
E       200
X       60