简体   繁体   English

如何获取多列的最大值(以及datecolumn为max的stringcolumn的值)并将其组合为单个查询?

[英]How can I get the max value of multiple columns (and value of stringcolumn where datecolumn is max) and combine it into a single query?

How can I do this in SQL? 如何在SQL中执行此操作?

This is my sample data: 这是我的示例数据:

ColA   ColB   ColC   ColD   ColE
----   ----   ----   ----   ----
TR12   25     67    yey
TR11   28     99    apr     2/2/2013
TR12   78     55    apr     2/2/2013
TR12   20     35    olf     2/5/2013

The condition is to get the max value in ColB and ColC of a certain value in ColA. 条件是在ColB中获得最大值,在ColC中获得某个值。

For ColD and ColE values, I would like to get them from the line where it has a maximum ColE value. 对于ColD和ColE值,我想从具有最大ColE值的行中获取它们。

 ColA   ColB   ColC   ColD   ColE
 ----   ----   ----   ----   ----
*TR12*  25     *67*  yey
 TR11   28     99    apr     2/2/2013
 TR12   *78*   55    apr     2/2/2013
 TR12   20     35    *olf*   *2/5/2013*

Hence, my expected result would be like this: 因此,我的预期结果将是这样的:

ColA   ColB   ColC   ColD   ColE
----   ----   ----   ----   ----
TR12   78     67     olf    2/5/2013

This is all I have as of now where it could return the correct max value of a column, but what about returning a string based on the line where ColE is max value ? 到目前为止,这就是我可以在其中返回列的正确最大值的全部功能,但是基于ColE是max value的行返回字符串呢? I am getting an incorrect value when I do max() function for ColD. 当我为ColD执行max()函数时,得到的值不正确。 I am getting the other word instead of the word where ColE is max. 我得到的是另一个单词,而不是ColE最大的单词。

SELECT 
   ColA, max(ColB) as ColB, max(ColC) as ColC,
   max(ColD) as ColD, -- this is where I got it wrong,
      this should return the string where its ColE is the maximum
   max(ColE) as ColE
FROM 
   dbo.SomeTable 
WHERE 
   ColA = 'TR12'

I really hope you could help me with this one.. 我真的希望您能帮到我。

thanks for the quick replies.. 感谢您的快速答复。

You are doing fine; 你还好 just keep going. 尽管继续。 The max() aggregate function works on strings as well as numerics. max()聚合函数适用于字符串以及数字。

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

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