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
270 views
in Technique[技术] by (71.8m points)

sql - SQlite fill empty cells

I am writing this query to calculate.

SELECT
Date,
SUM(CASE WHEN (Terms="Sandwich") THEN Stars ELSE 0 END) / SUM(CASE WHEN (Terms="Sandwich") THEN 1 ELSE 0 END) AS Sandwich,
SUM(CASE WHEN (Terms="Chicken") THEN Stars ELSE 0 END) / SUM(CASE WHEN (Terms="Chicken") THEN 1 ELSE 0 END) AS Chicken,
SUM(CASE WHEN (Terms="Meat") THEN Stars ELSE 0 END) / SUM(CASE WHEN (Terms="Meat") THEN 1 ELSE 0 END) AS Meat,
SUM(CASE WHEN (Terms="Others") THEN Stars ELSE 0 END) / SUM(CASE WHEN (Terms="Others") THEN 1 ELSE 0 END) AS Others
FROM __table__
GROUP BY Date

Original Data is this.

enter image description here

This is the result of query.

enter image description here

/ is used for int division so why the result is in float. Second issue is some times the count and sum of terms is 0 so 0/0 is undefined. I want to fill those cells with 0. Please update query.

question from:https://stackoverflow.com/questions/65624239/sqlite-fill-empty-cells

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

1 Reply

0 votes
by (71.8m points)

You can do it with conditional aggregation and COALESCE() so that you get 0 instead of NULL:

SELECT Date,
       COALESCE(AVG(CASE WHEN Terms = 'Sandwich' THEN Stars END), 0) Sandwich,
       COALESCE(AVG(CASE WHEN Terms = 'Chicken' THEN Stars END), 0) Chicken,
       COALESCE(AVG(CASE WHEN Terms = 'Meat' THEN Stars END), 0) Meat,
       COALESCE(AVG(CASE WHEN Terms = 'Others' THEN Stars END), 0) Others
FROM __table__
GROUP BY Date;

AVG() returns a float.
If you want the result as integers you can use:

CAST(COALESCE(AVG(CASE WHEN Terms = 'Sandwich' THEN Stars END), 0) AS INTEGER)

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

...