![](/img/trans.png)
[英]SQL - sum (column 1 + column2 + column3 ) and select max value of sum in each group
[英]SQL Server : get max of the column2 and column3 value must be 1
我有一个存储过程的部分输出,如下所示:
col1 col2 col3 col4
--------------------------
2016-05-05 1 2 2
2016-05-05 1 3 32
2016-05-12 2 1 11
2016-05-12 3 1 31
现在我需要根据这个条件得到结果
col2 = 1 and col3 = max or col3 = 1
and col2 = max
最终的结果应该是
col1 col2 col3 col4
-------------------------
2016-05-05 1 3 32
2016-05-12 3 1 31
不确定这是否是最有效的方式,但您可以使用ROW_NUMBER()
:
SELECT * FROM (
SELECT t.*,
ROW_NUMBER() OVER(PARTITION BY t.col1 ORDER BY t.col3 DESC) as rnk,
WHERE t.col2 = 1
UNION ALL
SELECT t.*,
ROW_NUMBER() OVER(PARTITION BY t.col1 ORDER BY t.col2 DESC) as rnk,
WHERE t.col3 = 1) tt
WHERE rnk = 1
这将为您提供所有记录
(col2=1 and col3=max) or (col3=1 and col2=max)
这有点棘手。 您的数据没有歧义,例如col4
重复col4
或col2
和col3
“1”值。
以下是您问题中逻辑的直接翻译:
select t.*
from t
where t.col4 = (select max(t2.col4)
from t t2
where t2.col1 = t.col1 and (t2.col2 = 1 or t2.col3 = 1)
);
尝试这个。 请注意,如果max
超过1,则需要输出中的所有值。 它适用于所有场景,即使col1
与col2
和col3
不同步。
我首先找到col2
和col3
最高值,并将它们赋值为1
。 然后在外部查询中,我正在使用您的连接条件。 为Postgres DB创建的演示作为SQLServer不可用。
select col1,col2,col3,col4
from
(
select t.*,
RANK() OVER(ORDER BY col3 DESC) as col3_max,
RANK() OVER(ORDER BY col2 DESC) as col2_max
from your_table t
) t1
where
(col2=1 and col3_max=1)
OR
(col3=1 and col2_max=1)
替代方式:
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY col1 ORDER BY iif(col2 = 1, col3, col2) DESC) as r
FROM tbl) t
WHERE r = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.