SQLite 3 : select and count together with group by and without group by

标签 sql sqlite

在这个问题之前 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/

相关文章:

python - 为什么 Twisted 的 adbapi 无法从单元测试中恢复数据?

java - SQLite中更新语句的问题

java - 如何从存储在 android 的 sqlite 数据库中的 blob 打开 pdf?

mysql - 按年按月按月生成统计

php - 如何防止 PHP 中的 SQL 注入(inject)?

php - mysql 插入突然停止在我的 php 代码中工作

python - CentOS/Bluehost : Attempt to Write a Readonly Database, 上的 Django 除 777 外还使用哪个 Chmod?

java - 单击android中的按钮时数据库导出到xls文件?

mysql - ORDER BY 日期在即将到来的日期之后的过去日期

c# - LINQ 从多个连接中获取具有最大日期的记录