sql - postgres:caseif值不存在sql
问题描述
我试图计算我的公司中营业额最好的前 10 名。我做了下面的代码。如果我的公司少于 10 家,我的问题是要做到最好。如果我的表营业额中有 < 10 家公司,我的查询将返回 NULL。如果我只有 8 家公司,我只想返回这 8 家公司中的佼佼者。(列总数)。
如果我不清楚,请告诉我!
代码
create table turnover (
id integer,
cat varchar(40),
date_ date,
total_ integer,
CONSTRAINT turnover_ UNIQUE(id, cat, date_));
create table contact (
id integer,
date_ date,
Type_ varchar(40),
total_ integer,
CONSTRAINT cnt UNIQUE(id, date_, type_));
select
id, cat, t_date, total_, c_date, type_, total_
from
(
select
t.id, t.cat, t.date_ "t_date", t.total_,
c.date_ "c_date", c.type_, c.total_
count(*) over (partition by t.date_) as cnt,
row_number() over (partition by t1.date_ order by t.total_ desc) as rn
from turnover t
inner join contact c on t.id = c.id
where t.cat = 'cat1' and t.total_ > 0
) t1
where t1.rn/t1.cnt<=0.10
解决方案
select
id,
cat,
t1.t_date,
t1.total_,
c_date,
type_,
total_
from
(
select
t.id,
t.cat,
t.date_ "t_date",
t.total_ as ttotal,
c.date_ "c_date",
c.type_,
c.total_,
count(*) over (partition by t.date_) as cnt,
row_number() over (partition by t.date_ order by t.total_ desc) as rn
from turnover t
inner join contact c on t.id = c.id
--where t.cat = 'cat1' and t.total_ > 0
) t1
limit 1
推荐阅读
- python - 如何在 Python 中装饰属性
- vb.net - 添加单引号
- regex - 使用正则表达式提取特定字符串
- go - Getting an error when trying to check path
- vbscript - Bamboo 作业无法执行带有 Microsoft SQL Server 连接字符串的 VBScript
- javascript - 匹配字符串到数组
- regex - Ansible 2.4 检查输出中的匹配“单词”
- node.js - 为什么 expressjs 从下面的代码在浏览器中返回错误“Cannot GET /”?
- angular - Angular - 动态组件
- javascript - 如何在不检索文档的情况下检查文档是否存在:Mongoose