max(columnname)给出错误的输出

时间:2016-03-24 11:08:58

标签: sql-server sql-server-2008

简单选择max函数给出错误的值。当我运行以下查询时,我得到的最大值为100,其中列中的最大值为11.我还有一个问题,当我运行此查询时,我得到更令人担忧的结果所有列值都出错了。我做错了什么。

SELECT MAX(强制转换([PT_100SCALED_VAL0]为十进制))FROM REPORT

SELECT t7.[timestamp], t7.[timestamp_utc], t7.[PT_100SCALED_VAL0], t7.[PT_101SCALED_VAL0],
 t7.[PT_102SCALED_VAL0], t7.[PT_103SCALED_VAL0], t7.[PT_104SCALED_VAL0], t7.[PT_105SCALED_VAL0],
  t7.[PT_200SCALED_VAL0], t7.[PT_201SCALED_VAL0], t7.[PT_300SCALED_VAL0] ,
   ( SELECT MAX([PT_100SCALED_VAL0]) FROM REPORT ) AS
    PT_100SCALED_VAL0_MAXIMUM FROM [REPORT] t7 
    Where  t7. [PT_100SCALED_VAL0]=100 
    group by t7.[timestamp],t7.[timestamp_utc],t7.[PT_100SCALED_VAL0],t7.[PT_101SCALED_VAL0],t7.[PT_102SCALED_VAL0],t7.[PT_103SCALED_VAL0],t7.[PT_104SCALED_VAL0],t7.[PT_105SCALED_VAL0],t7.[PT_200SCALED_VAL0],t7.[PT_201SCALED_VAL0],t7.[PT_300SCALED_VAL0]

下面是我的表格设计查询

USE [master]
GO

/****** Object:  Table [dbo].[REPORT]    Script Date: 03/24/2016 16:24:29 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[REPORT](
    [timestamp] [datetime] NULL,
    [timestamp_utc] [datetime] NOT NULL,
    [PT_100SCALED_VAL0] [float] NULL,
    [PT_101SCALED_VAL0] [float] NULL,
    [PT_102SCALED_VAL0] [float] NULL,
    [PT_103SCALED_VAL0] [float] NULL,
    [PT_104SCALED_VAL0] [float] NULL,
    [PT_105SCALED_VAL0] [float] NULL,
    [PT_200SCALED_VAL0] [float] NULL,
    [PT_201SCALED_VAL0] [float] NULL,
    [PT_300SCALED_VAL0] [float] NULL,
 CONSTRAINT [PK_REPORT] PRIMARY KEY CLUSTERED 
(
    [timestamp_utc] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

以下是我的表数据:

timestamp   timestamp_utc   PT_100SCALED_VAL0   PT_101SCALED_VAL0   PT_102SCALED_VAL0   PT_103SCALED_VAL0   PT_104SCALED_VAL0   PT_105SCALED_VAL0   PT_200SCALED_VAL0   PT_201SCALED_VAL0   PT_300SCALED_VAL0
2016-01-08 16:02:50.780 2016-01-08 10:32:50.780 11  22  33  44  55  66  0   0   0
2016-01-08 16:04:42.333 2016-01-08 10:34:42.333 11  22  33  44  55  66  0   0   0

1 个答案:

答案 0 :(得分:0)

如果您希望max()符合where条件,则使用窗口函数而不是子查询:

SELECT . . .
       MAX([PT_100SCALED_VAL0]) OVER () as PT_100SCALED_VAL0_MAXIMUM