如何在GROUP BY中将条件置于MAX中

时间:2018-01-12 11:22:46

标签: sql sql-server

我希望按日期对数据进行分组,然后为不同的“代码”找到最大“值”。我怎么能这样做 - 我想为MAX()提供一个条件,但我不认为这是可能的。

列:

Date: date
Time: time
Value: float
Code: varchar

SELECT MAX([Value] where [Code]='GOLD') AS BestGold, 
       MAX([Value] where [Code]='SILVER') AS BestSilver
FROM [MyTable]
GROUP BY [Date]

5 个答案:

答案 0 :(得分:1)

使用CASE表达式:

SELECT
    MAX(CASE WHEN [Code]='GOLD'   THEN ['Value'] END) AS BestGold,
    MAX(CASE WHEN [Code]='SILVER' THEN ['Value'] END) AS BestSilver
FROM [MyTable]
GROUP BY [Date];

这里的想法是MAX函数只会考虑每种代码类型的记录值。

答案 1 :(得分:0)

相反,请使用此

SELECT 
    [Date],
    [Code],
    MAX([Value]) AS Best
FROM [MyTable]
    where cODE IN ('GOLD','SILVER')
GROUP BY [Date]

如果您想将其作为单独列,请尝试透视相同的

;WITH CTE
AS
(
    SELECT 
       [Date],
       [Code],
       MAX([Value]) AS Best
    FROM [MyTable]
       where cODE IN ('GOLD','SILVER')
    GROUP BY [Date]
)
SELECT
    [Date],
    BestGold = [GOLD],
    BestSilver = [Silver]
    FROM CTE
    PIVOT
    (
       MAX(Best)
       FOR
       Code IN
       (
          [GOLD],[SILVER]
       )
    )P

答案 2 :(得分:0)

您可以使用内联iif

SELECT MAX(IIF([Code]='GOLD', [Value], null)) AS BestGold, 
       MAX(IIF([Code]='SILVER', [Value], null)) as BestSilver
FROM [MyTable]
GROUP BY [Date]

case

SELECT MAX(case [Code] when 'GOLD' then [Value] end) AS BestGold, 
       MAX(case [Code] when 'SILVER' then [Value] end) as BestSilver
FROM [MyTable]
GROUP BY [Date]

答案 3 :(得分:0)

我相信您需要以下内容: -

DECLARE @TestCodes Table
(
 Date date,
 Time time,
 Value float,
 Code varchar(10)
)

INSERT INTO @TestCodes
VALUES
('2017-08-09','12:00',19900,'Gold'),
('2017-08-09','12:00',15001,'Gold'),
('2017-08-09','12:00',2500,'Gold'),
('2017-08-09','12:00',1200.01,'Metal'),
('2017-08-09','12:00',1900,'Metal'),
('2017-08-09','12:00',1800.1,'Silver'),
('2017-08-09','12:00',1100.01,'Silver'),
('2017-08-09','12:00',100.11,'Silver')

SELECT Date,Code,Max(value) AS MAXPriceOnAnyDate
FROM @TestCodes
GROUP BY [Date],CODE

答案 4 :(得分:0)

您可以使用case;

SELECT
    MAX(CASE WHEN Code='GOLD'   THEN [VALUE] ELSE -1 END) AS BestGold,
    MAX(CASE WHEN Code='SILVER' THEN [VALUE] ELSE -1 END) AS BestSilver
FROM [MyTable]
GROUP BY [Date];