SQL 查询 - 创建时间序列(从 2 列创建序列)
作为一名 SQL 新手,你能帮帮我吗?
在 SQL(或 Google 的 BigQuery)当前表中:
Column A | Column B |
---|---|
2021-12-31 | null |
null | 2022-01-23 |
2009-04-12 | 2022-07-23 |
我的查询是错误的:
select
count(ColA) as A,
count(ColB) as B,
FORMAT_DATE('%Y %m', ColA) as month_year,
from myTable
group by month_year
所以我到目前为止:
Month_year | Count A | Count B |
---|---|---|
2021-12 | 1 | 0 |
我想做一个简单的计数,聚合年份的输出 月。正如您所看到的,由于我们使用的是 ColA 中的日期“数组”,因此我将丢失 B 栏的一些计数。
那么,如何对组合为年月分组的“聚合数组”的两列进行正确的计数。
我想要:
month_year | “计数”A | “计数”B |
---|---|---|
2009-04 | 1 | 0 |
2021-12 | 1 | 0 |
2022-01 | 0 | 1 |
2022-07 | 0 | 1 |
As a n00b in SQL, can you help me out.
In SQL (or Google's BigQuery) current table :
Column A | Column B |
---|---|
2021-12-31 | null |
null | 2022-01-23 |
2009-04-12 | 2022-07-23 |
My query which is wrong:
select
count(ColA) as A,
count(ColB) as B,
FORMAT_DATE('%Y %m', ColA) as month_year,
from myTable
group by month_year
so i've got so far :
month_year | Count A | Count B |
---|---|---|
2021-12 | 1 | 0 |
the output i'd like to do a simple count, aggregated year month. As you can see i will be missing some counts on col B since we are using the 'array' of dates from ColA.
So how can I make a proper count on both columns combined as the 'aggregate array' for the year month grouping.
i want :
month_year | "Count" A | "Count" B |
---|---|---|
2009-04 | 1 | 0 |
2021-12 | 1 | 0 |
2022-01 | 0 | 1 |
2022-07 | 0 | 1 |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请尝试以下操作:
合并函数允许您返回一个不为空的值。需要注意的是,如果两列都具有不同月份的值,则此解决方案可能无法按预期工作。
Try the following:
The coalesce function allows you to return a value that is not null. As a caveat this solution may not work as expected if both columns have a value for both columns that are in different months.
您可以尝试这个(MS SQL)
演示链接 https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=0fe2e9995a7040f8aaeecd8339012ee3
You can try this (MS SQL)
DEMO LINK https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=0fe2e9995a7040f8aaeecd8339012ee3
请考虑以下方法
如果应用于问题
输出中的示例数据,
Consider below approach
if applied to sample data in your question
output is