在这个问题之前 Sqlite 3 Insert and Replace fails on more than 1 unique column
我有一个带有架构的表,
CREATE TABLE tbl_poll (
id INTEGER PRIMARY KEY AUTOINCREMENT,
poll_id STRING NOT NULL,
ip_address STRING NOT NULL,
opt STRING NULL,
CONSTRAINT 'unique_vote_per_poll_per_ip_address' UNIQUE ( poll_id, ip_address ) ON CONFLICT REPLACE
);
当我这样做的时候,
select opt,count(opt) as count from tbl_poll where poll_id = 'jsfw' group by opt
结果是
opt count
0 4
2 2
3 2
即4个用户选择了0个选项,2个和2个用户分别选择了2和3个选项。
有什么办法可以得到如下结果
opt count percent
0 4 0.5
2 2 0.25
3 2 0.25
其中百分比 = 计数/总计数
如果我能得到总计数,即 (4+2+2 = 8 ),那也能解决我的问题。
我已经尝试过了,
select opt,count(opt) as count from tbl_poll where poll_id = 'jsfw'
但它不起作用,因为没有列不相同。
最佳答案
SELECT opt
, COUNT(*) AS count
, ROUND(CAST(COUNT(*) AS REAL)/total, 2) AS percent
FROM tbl_poll
CROSS JOIN
( SELECT COUNT(*) AS total
FROM tbl_poll
WHERE poll_id = 'jsfw'
) AS t
WHERE poll_id = 'jsfw'
GROUP BY opt ;
关于SQLite 3 : select and count together with group by and without group by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972599/