Max by Group

时间:2009-02-08 18:13:44

标签: sql sql-server aggregate-functions greatest-n-per-group

SELECT tblIssue.SYMB, tblIssue.[PRCE], tblIssue.[Shareholder]
FROM tblIssue

我试图为每个符号的最大股东数量拉出符号和价格。例如,我只有1行ASN,价格为60.62美元。

SYMB    Price   Shareholder
ASN $0.00   0
ASN $0.00   51
ASN $25.18  0
ASN $25.26  0
ASN $36.00  0
ASN $60.62  231
ASNL    $0.00   101
ASR $0.00   4
ASR $0.00   24
ASR $37.17  13

6 个答案:

答案 0 :(得分:3)

SELECT i1.*
FROM tblIssue i1
  LEFT OUTER JOIN tblIssue i2
  ON (i1.[SYMB] = i2.[SYMB] AND i1.[Shareholder] < i2.[Shareholder])
WHERE i2.[SYMB] IS NULL;

这是我使用这些问题的一个技巧:当没有其他行i1具有相同的i2和更大的{{}时,向我显示与[SYMB]对应的行1}}。即如果不存在具有更大[Shareholder]的行,则[Shareholder]必须具有最大值。

当每个不同的i1值的[Shareholder]值最高时,此查询会返回多行,但此线程中其他人给出的大多数其他答案也是如此。要解决此问题,您必须使用表的唯一列为连接添加另一个条件。

答案 1 :(得分:2)

相关子查询似乎最简单(如果我理解你的问题):

select symb, price, shareholder
from issue i
where price = ( select max(price) from issue where symb = i.symb)

产生:

ASN 61 231
ASNL 0 101
ASR 37 13

答案 2 :(得分:1)

WITH mx AS (
    SELECT tblIssue.SYMB, MAX(tblIssue.[Shareholder])
    FROM tblIssue
)
SELECT tblIssue.SYMB, tblIssue.[PRCE], tblIssue.[Shareholder]
FROM tblIssue
INNER JOIN mx
    ON mx.SYMB = tblIssue.SYMB
    AND mx.[Shareholder] = tblIssue.[Shareholder]

这应该产生:

SYMB    Price   Shareholder
ASN $60.62  231
ASNL    $0.00   101
ASR $0.00   24

如果那就是你要找的东西。

答案 3 :(得分:0)

在Oracle中:

SELECT symb, price
FROM (
  SELECT symb, price, ROW_NUMBER() OVER (PARTITION BY symb ORDER BY price DESC) AS rn
  FROM   tblIssue
)
WHERE rn = 1

答案 4 :(得分:0)

那会有所帮助;

Select * From tblIssue t2
Join 
(
Select MAX(t1.Shareholder) shrhldr, t1.symb symb
From tblIssue t1
Group by t1.symb
) tt On tt.shrhldr = t2.Shareholder and tt.symb = t2.symb

答案 5 :(得分:0)

这与Quassnoi的答案类似,但更正为获得最大股东行,这是OP所要求的。如果同一个符号的多行具有相同数量的最大股东,则会随机给您一个。如果你想要全部,请将ROW_NUMBER改为RANK。

SELECT symb, price, shareholder
FROM (
  SELECT symb, price, shareholder, ROW_NUMBER() OVER (PARTITION BY symb ORDER BY shareholder DESC) AS rn
  FROM   tblIssue
)
WHERE rn = 1