在SQL Server 2014 Management Studio中对行进行分组时检索单个字符串值

时间:2016-06-17 20:31:33

标签: sql sql-server

我有一个查询,我正在尝试从一组包含字符串值的列中将行组合在一起。我知道我可以用字符串值连接列,但我希望能够报告单个单元格值而不是该组中的所有值。

以下是我正在寻找的示例表和结果:

表:

ID_Number       Code    Rating
------------------------------
12345678901112  V       100
12345678901113  V       200
12345678901114  H       320
12345678981112  V       300
12345678981113  V       200
12345699981113  D       700

到目前为止的查询:

SELECT 
    LEFT(Ex.ID_Number, 10) AS ID_Number, 
    ???(Ex.Code) AS Code, 
    MAX(Ex.Rating) AS Rating
FROM 
    dbo.Exampletable Ex
GROUP BY 
    LEFT(Ex.ID_Number, 10);

期望的结果:

ID_Number   Code    Rating
---------------------------
1234567890  H       320
1234567898  V       300
1234569998  D       700

我目前的成绩:

ID Number   Code    Rating
---------------------------
1234567890  NULL    320
1234567898  NULL    300
1234569998  NULL    700

2 个答案:

答案 0 :(得分:1)

获得预期结果集的一种方法是使用ROW_NUMBER

SELECT ID_Number, Code, Rating
FROM (
  SELECT ROW_NUMBER() OVER (PARTITION BY LEFT(Ex.ID_Number,10) 
                            ORDER BY Rating DESC) AS rn,
         LEFT(ID_Number,10) AS ID_Number, Code, Rating
  FROM dbo.Exampletable ) AS t
WHERE t.rn = 1

在MySQL中,您可以使用连接到包含已聚合的Rating值的派生表:

SELECT LEFT(t1.ID_Number,10) AS ID_Number,
       t1.Rating, t1.Code
FROM Exampletable AS t1
JOIN (
  SELECT LEFT(Ex.ID_Number,10) AS ID_Number, MAX(Ex.Rating) AS Rating
  FROM Exampletable 
  GROUP BY LEFT(Ex.ID_Number,10)
) AS t2 ON LEFT(t1.ID_Number,10) = t2.ID_Number AND t1.Rating = t2.Rating

答案 1 :(得分:1)

要获得所需的结果,您可以通过ID_NumberRating将现有结果与现有表格结合使用。为此,您可以使用CTE。此解决方案适用于SQL Server

;WITH CTE_Result
AS
(   SELECT 
       LEFT(Ex.ID_Number,10) AS ID_Number, 
       MAX(Ex.Rating) AS Rating
    FROM dbo.Exampletable Ex
    GROUP BY LEFT(Ex.ID_Number,10)
)

SELECT CR.ID_Number, Ex.Code, CR.Rating
FROM CTE_Result CR
INNER JOIN dbo.Exampletable Ex 
   ON ID_Number = LEFT(Ex.ID_Number,10) AND Ex.Rating = CR.Rating

MySQL解决方案的更新

SELECT
    CR.ID_Number, Ex.Code, CR.Rating
FROM
(   SELECT 
       LEFT(Ex.ID_Number,10) AS ID_Number, 
       MAX(Ex.Rating) AS Rating
    FROM dbo.Exampletable Ex
    GROUP BY LEFT(Ex.ID_Number,10)
) CR
INNER JOIN dbo.Exampletable Ex 
   ON ID_Number = LEFT(Ex.ID_Number,10) AND Ex.Rating = CR.Rating