-1

我怎样才能选择这样的?我可以创建用户定义的聚合函数吗

SELECT Max(A),(SELECT TOP 1 FROM TheGroup Where B=Max(A))从我的表

其中 MyTable 如下图所示

    A  B  C
--------------
    1  2  S
    3  4  S
    4  5  T
    6  7  T

我想要这样的查询

SELECT MAX(A),(B Where A=Max(A)),C FROM MYTable GROUP BY C

我期待结果如下

 MAX(A)  Condition    C
-----------------------
   3        4         S
   6        7         T
4

6 回答 6

2
 SELECT A,B,C FROM
     (SELECT *, ROW_NUMBER() OVER (PARTITION BY C ORDER BY A DESC) RN FROM MyTable)
 WHERE RN = 1

(此查询将始终为每个 C 值返回一行)

或者

WITH CTE_Group AS 
(
    SELECT C, MAX(A) AS MaxA
    FROM MyTable
    GROUP BY C
)
SELECT g.MaxA, t.B, g.C
FROM MyTable t
INNER JOIN CTE_Group g ON t.A = g.MaxA AND t.C = g.C

(如果有多行具有相同的 Max(A) 值 - 此查询将返回所有行)

于 2013-07-09T13:20:13.677 回答
1
SELECT Max(A)
FROM MyTable
Where B=(SELECT Max(A) FROM MyTable) 

更新:

SELECT *
FROM MyTable
Where B=(SELECT Max(A) FROM MyTable) 

更新2:

SELECT DISTINCT A, B
FROM MyTable
Where A=(SELECT Max(A) FROM MyTable GROUP BY C) 

更新 3:

好的,我想我明白你现在在找什么了.. 这个怎么样:

SELECT *
FROM MyTable
Where A in (SELECT Max(A) FROM MyTable GROUP BY C) 
于 2013-07-09T12:59:41.740 回答
1
SELECT t1.*
FROM YourTable t1 
Left Outer Join YourTable t2 on t1.C=t2.C AND t1.A < t2.A
WHERE t2.A is null
于 2013-07-09T13:05:25.563 回答
1
WITH
  cte AS
(
  SELECT 
    ROW_NUMBER() OVER (ORDER BY cola desc) AS Rno,
    *
  FROM
    tbl
)
SELECT top 1
cola,colb
FROM
  cte
order by Rno

那就试试吧:

    WITH
  cte AS
(
  SELECT 
    ROW_NUMBER() OVER (PARTITION BY col3 ORDER BY col1 desc) AS Rno,
    *
  FROM
    tbl

)
SELECT 
col1,col2,col3
FROM
  cte
WHERE Rno=1
于 2013-07-09T13:07:43.877 回答
1

这个怎么样:

    SELECT *
    FROM MyTable    
    WHERE A IN (SELECT MAX(A) FROM MyTable GROUP BY C)
于 2013-07-09T13:28:01.667 回答
1

尝试以下查询:

SELECT TABLE1.A , TABLE2.B , TABLE1.C
FROM 
(
    SELECT MAX(A) AS A,C 
    FROM MYTable 
    GROUP BY C
) AS TABLE1 
INNER JOIN
(
SELECT *
FROM MYTable
) AS TABLE2 ON TABLE1.A = TABLE2.A

SQLFIDDLE

你可以通过简单的连接查询来做到这一点。join 查询总是比 In query 运行得更快。连接查询在执行查询时只运行一次。我们可以使用 IN query 归档相同的结果。

于 2013-07-09T13:44:39.450 回答