我对sqlite的查询有问题。我想要做的是两列的平均值,并将结果放在一个新列中。例如:
id | max_ma | max_ta | avg_max (new column)
1 | 100 | 102 | 101 ==> (100+102)/2
2 | 100 | null | 100 ==> (100+0)/1 INGNORE NULL
错误的代码:
public Cursor list() {
String lista_ge = "SELECT *, AVG(tr_max_m + tr_max_t) AS media_max FROM bdt_registro ORDER BY tr_fecha DESC, _id DESC";
return db.rawQuery(lista_ge, null);
}
或
public Cursor list() {
String lista_ge = "SELECT *, ((tr_max_m + tr_max_t)/COUNT(*)) AS media_max FROM bdt_registro ORDER BY tr_fecha DESC, _id DESC";
return db.rawQuery(lista_ge, null);
}
感谢您的关注
答案 0 :(得分:1)
可能最好的方法是使用很多案例:
SELECT max_ma, max_ta,
CASE WHEN max_ma IS NULL THEN
CASE WHEN max_ta IS NULL THEN 0
ELSE max_ta END
ELSE
CASE WHEN max_ta IS NULL THEN max_ma
ELSE (max_ma + max_ta) / 2 END
END avg_max
FROM user_address
小提琴here。
顺便说一句,我注意到你正在尝试使用AVG
。如果您想知道如何使用该功能,那么这将给您一个想法。它不会比以前的方法更快,因为它增加了更多的计算,但是:
SELECT id,
max(CASE WHEN kind = 1 THEN aMax END) max_ma,
max(CASE WHEN kind = 2 THEN aMax END) max_ta,
avg(aMax) aMax
FROM (
SELECT id, max_ma aMax, 1 kind FROM user_address
UNION ALL
SELECT id, max_ta, 2 FROM user_address
) s
GROUP BY id
答案 1 :(得分:1)
使用COALESCE功能:
SELECT *,
(COALESCE(tr_max_m, tr_max_t, 0) + COALESCE(tr_max_t, tr_max_m, 0)) / 2 AS media_max
FROM
bdt_registro ORDER BY tr_fecha DESC, _id DESC
NULL
,则会获得:(tr_max_t + tr_max_m) / 2
tr_max_m
为NULL
,则会获得:(tr_max_t + tr_max_t) / 2 = tr_max_t
tr_max_t
为NULL
,则会获得:(tr_max_m + tr_max_m) / 2 = tr_max_m
NULL
,则会获得:(0 + 0) / 2 = 0
答案 2 :(得分:0)
另一种基于函数IFNULL
和...
...“未汇总”汇总函数COUNT
:
SELECT *,
(IFNULL(max_ma, 0)+IFNULL(max_ta, 0))/(COUNT(max_ma)+COUNT(max_ta)) AS avg_max
FROM bdt_registro
GROUP BY id;
... CASE
:
SELECT *,
(IFNULL(max_ma, 0)+IFNULL(max_ta, 0)) / (CASE WHEN max_ma IS NULL THEN 0 ELSE 1 END + CASE WHEN max_ta IS NULL THEN 0 ELSE 1 END) AS avg_max
FROM bdt_registro;