我有下面提到的表:
ID Var1 Date
A-1 5 2017-04-01 18:45:05
A-2 8 2017-04-01 18:45:05
A-3 5 2017-04-01 18:45:05
A-3 5 2017-04-02 18:45:05
A-4 8 2017-04-02 18:45:05
A-5 8 2017-04-02 18:45:05
A-6 8 2017-04-03 18:45:05
我想计算每天ID
Var1
值8
为SELECT
COUNT( ID) AS ID,
((COUNT( Var1) / (COUNT( ID) )) * 100 ) AS percentage
FROM
Table1
WHERE Var1=8
GROUP BY
Date(Date);
的百分比。
我试过了,但它无法工作。
db.feed.find({
"_id" : {
"$in" :
[ObjectId("55880c251df42d0466919268"),
ObjectId("55bf528e69b70ae79be35006")
]
}
});
答案 0 :(得分:1)
drop table if exists t;
create table t (ID varchar(3), Var1 int, Dt datetime);
insert into t values
('A-1' , 5 , '2017-04-01 18:45:05'),
('A-2' , 8 , '2017-04-01 18:45:05'),
('A-3' , 5 , '2017-04-01 18:45:05'),
('A-3' , 5 , '2017-04-02 18:45:05'),
('A-4' , 8 , '2017-04-02 18:45:05'),
('A-6' , 8 , '2017-04-03 18:45:05');
select dt,count(id) NofID,
sum(case when var1 = 8 then 1 else 0 end) nofeights,
(sum(case when var1 = 8 then 1 else 0 end) / count(id)) * 100 eights
from t
group by dt;
+---------------------+-------+-----------+----------+
| dt | NofID | nofeights | eights |
+---------------------+-------+-----------+----------+
| 2017-04-01 18:45:05 | 3 | 1 | 33.3333 |
| 2017-04-02 18:45:05 | 2 | 1 | 50.0000 |
| 2017-04-03 18:45:05 | 1 | 1 | 100.0000 |
+---------------------+-------+-----------+----------+
3 rows in set (0.00 sec)
答案 1 :(得分:1)
我建议将其写成:
SELECT Date(Date), SUM(Var1 = 8) AS ID,
AVG(Var1 = 8) * 100 AS percentage
FROM Table1
GROUP BY Date(Date);
这使用MySQL快捷方式,允许在数字上下文中将布尔值视为数字。