sql函数,可以查看和聚合两列之间的差异

时间:2015-01-01 18:08:10

标签: sql-server tsql sql-server-2012 user-defined-functions

我有一张这样的表:

create table Stuff
(StuffID int identity not null,
 StuffPrice decimal (8,2) not null,
 StuffSold decimal (8,2) not null,
 StuffPriceTime datetime not null)

我想做一个查询,显示我正在返回的记录集,StuffPrice大于StuffSold的次数。有没有SQL批处理方式这样做?类似的东西:

Select
 StuffID,
 StuffPrice,
 StuffSold,
 StuffPriceTime,
 SomeFunction(StuffPrice,StuffSold)
From Stuff

我看到的结果集看起来像是:

[StuffID] - [StuffPrice] - [StuffSold] - [StuffPriceTime] - [True/False Result]

既然我正在写这篇文章,我想我可以做一个UDF标量函数,但我听说这些表现对于那些人来说可能很糟糕。

1 个答案:

答案 0 :(得分:4)

通常,可以表示为逻辑表达式(谓词)的列之间的任何差异都可以表示为标记 - CASE WHEN predicate=true THEN 1 ELSE 0 END,然后汇总到最终结果。

例如:

create table Stuff
(StuffID int identity not null,
 StuffPrice decimal (8,2) not null,
 StuffSold decimal (8,2) not null,
 StuffPriceTime datetime not null)

 insert into Stuff (StuffPrice, StuffSold, StuffPriceTime) values
 (10.0, 11.0, getdate()), --> lower
 (12.0, 11.0, getdate()), --> greater
 (17.0, 18.0, getdate()), --> lower
 (17.0, 16.0, getdate()); --> greater

Select
 StuffID,
 StuffPrice,
 StuffSold,
 StuffPriceTime,
 sum(case when StuffPrice > StuffSold then 1 else 0 end) over() [number of times]
From Stuff

结果:

StuffID StuffPrice  StuffSold   StuffPriceTime  [number of times]
-----------------------------------------------------------------
1       10.00       11.00       2015-01-01      2
2       12.00       11.00       2015-01-01      2
3       17.00       18.00       2015-01-01      2
4       17.00       16.00       2015-01-01      2