在这个问题之前 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'
但它不起作用,因为没有列不相同。
答案 0 :(得分:3)
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 ;
答案 1 :(得分:0)
如果您知道opt中的所有可能值,则可以使用CASE WHEN
声明:
SELECT COUNT(opt) as total, SUM(CASE WHEN opt = '0' OR opt IS NULL OR TRIM(opt) = '' THEN 1 ELSE 0 END) as total0, SUM(CASE WHEN opt = '1' THEN 1 ELSE 0 END) as total1, ... FROM tbl_poll WHERE poll_id = 'jsfw'
这会给你:
total total0 total1 ...
8 4 0 ...
如果这不是一组封闭的选项,请告诉我。
sintax如下:
CASE WHEN condition THEN result_for_true ELSE result_for_false END
CASE WHEN condition1 THEN result_for_1 WHEN condition2 THEN result_for_2 ELSE result_for_false_on_all END