【问题标题】:sql function that can see, and aggregate, differences between two columns可以查看和聚合两列之间差异的 sql 函数
【发布时间】:2015-01-01 18:08:09
【问题描述】:

我有一张这样的桌子:

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 标量函数,但我听说这些函数的性能可能很糟糕。

【问题讨论】:

  • 关于聚合部分,如果真/假返回为 0/1,我可以 SUM()。

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


【解决方案1】:

一般来说,列之间任何可以表示为逻辑表达式(谓词)的差异,都可以表示为标志-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

【讨论】:

    猜你喜欢
    • 2021-10-21
    • 2022-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多