【发布时间】:2020-06-25 00:57:55
【问题描述】:
我已经编写了一个 SQL 语句,它产生天数并计算每个天数。
我想要完成的是 10 天以上和以下的计数和百分比。
以下示例数据以及我希望在彩色文本中实现的目标。
非常感谢您的帮助。
【问题讨论】:
标签: sql-server database tsql
我已经编写了一个 SQL 语句,它产生天数并计算每个天数。
我想要完成的是 10 天以上和以下的计数和百分比。
以下示例数据以及我希望在彩色文本中实现的目标。
非常感谢您的帮助。
【问题讨论】:
标签: sql-server database tsql
如果你只想要最后两天,你可以使用:
select (case when days_take <= 10 then '10 or less' else 'greater than 10' end) as grp,
count(*) * 100.0 / sum(count(*)) over () as percentage,
count(*) as ratio
from t
group by (case when days_take <= 10 then '10 or less' else 'greater than 10' end);
【讨论】:
在 TSQL 中,可以使用cross apply 和聚合:
你可以做条件聚合:
select
x.descr,
1.0 * sum(x.how_many) / sum(sum(x.how_many)) over() as how_many_ratio,
sum(x.how_many) as how_many_value
from mytable t
cross apply (values
(
'greater than 10 days'
case when days_taken > 10 then how_many else 0 end
),
(
'less than and 10 days'
case when days_taken <= 10 then how_many else 0 end
)
) as x(descr, how_many)
group by x.descr
如果您满足于将所有结果放在一行中,则条件聚合更简单:
select
1.0 * sum(case when days_taken > 10 then how_many else 0 end)
/ sum(how_many) as how_many_above_10_ratio,
sum(case when days_taken > 10 then how_many else 0 end) as how_many_above_10,
1.0 * sum(case when days_taken <= 10 then how_many else 0 end)
/ sum(how_many) as how_many_below_10_ratio,
sum(case when days_taken <= 10 then how_many else 0 end) as how_many_below_10
from mytable
【讨论】: