Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

sql - Average on most recent date for which data is available for multiple columns

I have a table (on BigQuery) that looks like the following:

|    Date    |    Type    |    Score1   |    Score2   |
|------------|------------|-------------|-------------|
| 2021-01-04 |      A     |      5      |     NULL    |
| 2021-01-04 |      A     |      4      |     NULL    |
| 2021-01-04 |      A     |      5      |     NULL    |
| 2021-01-02 |      A     |      1      |     NULL    |
| 2021-01-02 |      A     |      1      |     NULL    |
| 2021-01-01 |      A     |      3      |      2      |
| 2021-01-04 |      B     |     NULL    |      3      |
| 2021-01-04 |      B     |     NULL    |     NULL    |
| 2021-01-02 |      B     |     NULL    |      4      |
| 2021-01-02 |      B     |     NULL    |      4      |
| 2021-01-01 |      B     |      2      |      5      |
| 2021-01-01 |      B     |      5      |      3      |
| 2021-01-04 |      C     |     NULL    |     NULL    |
| 2021-01-04 |      C     |      4      |     NULL    |
| 2021-01-04 |      C     |     NULL    |     NULL    |
| 2021-01-01 |      C     |      1      |      5      |
| 2021-01-01 |      C     |      2      |      4      |
| 2021-01-01 |      C     |      3      |      4      |

What I would like to get is the average score for each type but the average should be taken only on the most recent date for which at least one score is available for the type. From the example above, the aim is to obtain the following table in one query (that can contain subqueries):

|    Type    |  AVG Score1 |  AVG Score2 |
|------------|-------------|-------------|
|      A     |  (5+4+5)/3  |    (2)/1    |
|      B     |   (2+5)/2   |    (3)/1    |
|      C     |    (4)/1    |  (5+4+4)/3  |

I need a solution that could be adapted if I want the average score, not for each type, but for each combination of two columns (type/color), still on the most recent date for which at least one score is available for the combination. It should be also possible to adapt it if I have more score columns and for different aggregations (AVG/MAX/MIN...).

N.B.: A first question was asked to handle the same problem with only one score column: Average on the most recent date for which data is available.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...