sql 可以查看和聚合两列之间差异的函数
sql function that can see, and aggregate, differences between two columns
我有一个 table 这样的:
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 标量函数,但我听说这些函数的性能可能很糟糕。
一般来说,任何一种可以表示为逻辑表达式(谓词)的列之间的差异都可以表示为标志 - 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
我有一个 table 这样的:
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 标量函数,但我听说这些函数的性能可能很糟糕。
一般来说,任何一种可以表示为逻辑表达式(谓词)的列之间的差异都可以表示为标志 - 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