在SQL(Derby)数据库中统计两个不同列中的布尔值。

huangapple go评论82阅读模式
英文:

counting booleans in 2 different columns of sql (derby) database

问题

以下是您要翻译的内容:

我是Java和SQL的新手,对一个混淆了我的数据的查询感到困惑。我有一个包含3列的简单表格(IDI(整数),column1(布尔),column2(布尔))。

我已经想出了可以成功运行的查询,但数据会在这两个布尔列之间复制。如果我运行select * from booleans,所有的数据都是正确的,但是当我编写一个查询来计算每一列的数量(总数)时,两列的总数却相同?

当我运行下面的查询时,我得到了如图所示的正确结果:

select * from booleans order by idi

然而,当我尝试计算和分组时,两列的数据都相同。每一列应该有一个数字,另一列为0。以下是代码和结果图片:

select idi, count(column1) as "Column 1", count(column2) as "Column2" 
from booleans  
group by idi

我将不胜感激,如果有任何关于为什么在聚合表中显示不正确的理论。

英文:

I am new to Java and SQL and am stumped by a query that is mixing up my data.
I have a simple table with 3 columns (IDI (integer), column1 (bool), column2 (bool)).

I have come up with queries that will succeed but with data being copied between the 2 boolean columns. If I do select * from booleans all the data is correct but when I write a query to count (total) each column the totals come out the same?

When I run this query I get correct results as shown in image;

select * from booleans order by idi

在SQL(Derby)数据库中统计两个不同列中的布尔值。

However, when I try to count and group both columns have the same data. Each column should have a number in one column and a 0 in the other. Here is the code and picture of the results:

select idi, count(column1) as "Column 1", count(column2) as "Column2" 
from booleans  
group by idi

在SQL(Derby)数据库中统计两个不同列中的布尔值。

I would appreciate any theories as to why this is displaying incorrectly in the aggregated table.

答案1

得分: 2

为了仅计算 true 值,排除 false 值,您可以执行以下操作:

select idi,
  sum(case when column1 then 1 else 0 end) as count1,
  sum(case when column2 then 1 else 0 end) as count2
from booleans
group by idi

详细说明:count(*) 函数计算有多少个 非空值。对于此函数,值是 true 还是 false 并不重要。

英文:

In order to count only true values, excluding the false ones you can do:

select idi,
  sum(case when column1 then 1 else 0 end) as count1,
  sum(case when column2 then 1 else 0 end) as count2
from booleans
group by idi

To elaborate: count(*) counts how many non-null values are there. For this function, it doesn't matter if the values are true or false.

huangapple
  • 本文由 发表于 2020年8月23日 11:00:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63542976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定