二进制过滤器,用于SQL查询的最大值

时间:2016-07-21 16:43:06

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

我正在使用Microsoft SQL Server Management Studio。我是SQL的新手,甚至不知道如何开始解决这个问题所以我提前为缺乏已经尝试过的解决方案道歉。我当前SQL查询的简化示例如下:

USE [DataBase]
GO
SELECT [ID]
      ,[Value1]
      ,[Max1]
      ,[Value2]
      ,[Max2]
FROM [DataTable]

产生类似的东西:

[ID] [Value1] [Max1] [Value2] [Max2]
[1]    [2]     [0]      [9]     [1]
[1]    [4]     [0]      [3]     [0]
[1]    [8]     [1]      [5]     [0]
[1]    [5]     [0]      [6]     [0]
[2]    [1]     [0]      [1]     [0]
[2]    [6]     [1]      [4]     [0]
[2]    [3]     [0]      [3]     [0]
[2]    [2]     [0]      [5]     [1]

我试图让我的数据表(DataTable)选择对应于二进制指示符的值(分别为Value1和Value2的Max1和Max2列),它是该ID的最大值。基本上我试图让上表成为:

[ID] [Value1] [Value2]
[1]    [8]      [9]
[2]    [6]      [5]

如果为每个变量创建一个单独的数据框要简单得多(Value1在一个单独的结果数据框中作为Value2),那也没关系。

谢谢

2 个答案:

答案 0 :(得分:1)

SELECT [ID]
      ,MAX([Value1]) as Value1
      ,MAX([Value2]) as Value2
FROM [DataTable]
GROUP BY
    [ID]

答案 1 :(得分:1)

您可以使用条件聚合来获取与二进制值1对应的值。

select 
[ID]
,max(case when [Max1] = 1 then [Value1] end) as value1
,max(case when [Max2] = 1 then [Value2] end) as value2
from [DataTable]
group by [ID]