【问题标题】:SQL - How To Add Rows Between a Range of Numbers and Make Their Value 0SQL - 如何在一系列数字之间添加行并使其值为 0
【发布时间】:2020-08-04 23:16:10
【问题描述】:
SQL Query I Am Working With
Result from the table
我想要完成的是,我想让它显示最小值和最大值之间的所有潜在 num_opens 值,而不是只为实际计算 num_opens 的地方提供值,并且它们的总数为 0。对于例如,在照片中我们看到了一个跳转
打开次数:7 总计:1
打开次数:10 总计:1
但我希望它是
打开次数:7 总计:1
打开次数:8 总数:0
打开次数:9 总计:0
打开次数:10 总计:1
对于最小值和最大值 (11 - 15, 15 - 31, 31 - 48) 之间的所有潜在 num_opens 值,同样如此。这很棘手,因为每天的最大值可能不同(今天最大值是 48,但明天可能是 37),所以我需要以某种方式拉取最大值。
谢谢!
【问题讨论】:
标签:
mysql
sql
google-bigquery
【解决方案1】:
您可以使用generate_array() 和unnest():
select num_opens, count(t.num_opens)
from (select min(num_opens) as min_no, max(num_opens) as max_no
from t
) x cross join
unnest(generate_array(t.min_no, t.max_no)) num_opens left join
t
on t.num_opens = num_opens
group by num_opens;
【解决方案2】:
您需要一个参考表才能开始。从您的图片中,您可以看到名为 users 的东西,但实际上任何(足够大的)桌子都可以。
首先,您将使用rank() 或row_count() 函数构建引用表。或者,如果您的 users.id 没有空白,则使用它会更容易。
SELECT *, rank() OVER (ORDER BY id) as reference_value FROM users
这将为users 生成一个表1....n。
现在你加入它,但从加入表中计数:
SELECT
a.reference_value, count(b.num_opens) as total
FROM
(SELECT rank() OVER (ORDER BY id) as reference_value from users) a
LEFT JOIN
[whatever table] b ON a.reference_value = b.num_opens
GROUP BY
a.reference_value
但这行太多了!您肯定拥有比这些事件计数更多的用户。所以在里面放一个快速过滤器。
SELECT
a.reference_value, count(b.num_opens) as total
FROM
(SELECT rank() OVER (ORDER BY id) as reference_value from users) a
LEFT JOIN
[whatever table] b ON a.reference_value = b.num_opens
WHERE
a.reference_value <= (SELECT max(num_opens) FROM [whatever table])
GROUP BY
a.reference_value