0

我有一个包含多列的信息表,但每列只能包含 3 个值中的 1 个(0、1、2)。它是通过用户输入的 Yes, No Maybe 选项生成的。我想计算每一列并反馈这些值。

EG表:

ID  Coffee  Tea   Water   Hot_Choc
1      1     0      2        2
2      0     2      0        1
3      1     2      0        2
4      2     0      1        1
5      1     1      2        2
6      0     1      2        1
7      2     1      0        1
8      1     2      1        2

我想将数据查询到这样的输出:

    Coffee  Tea   Water   Hot_Choc
0      2     2      3        0
1      4     3      2        4
2      2     3      3        4

我尝试运行基本计数脚本:SELECT coffee, count(*) FROM Drinks GROUP BY coffee

哪个工作正常。

然后尝试演变成:SELECT coffee,tea,water,hot_choc, count(*) from Drinks group by coffee,tea,water,hot_choc

但是有了这个,我得到了每个实例的计数。因此,当咖啡为 0 时,茶、水和 hot_choc 的数量是多少。

我还尝试了 sum(iif 子句,因为我正在访问:

select sum(iif(coffee=0,1,0)) as coffee_maybe,
sum(iif(coffee=1,1,0)) as coffee_no,
sum(iif(coffee=2,1,0)) as coffee_yes from drinks;
etc.

这让我明白了:

Coffee_maybe coffee_no coffee_yes tea_maybe tea_no tea_yes etc...
     2            4        2         2        3       2

所以我想知道是否有人对如何以上述格式获得计数有其他想法。

非常感谢您的帮助,对不起,我想提供尽可能多的背景信息。

4

1 回答 1

0

我认为以下内容将在 Access 中起作用:

select 0, sum(iif(coffee = 0, 1, 0)) as coffee, sum(iif(tea = 0, 1, 0)) as tea,
       sum(iif(water = 0, 1, 0)) as water, sum(iif(hot_choc = 0, 1, 0)) as hot_choc
from drinks d
union all
select 1, sum(iif(coffee = 1, 1, 0)) as coffee, sum(iif(tea = 1, 1, 0)) as tea,
       sum(iif(water = 1, 1, 0)) as water, sum(iif(hot_choc = 1, 1, 0)) as hot_choc
from drinks d
union all
select 2, sum(iif(coffee = 2, 1, 0)) as coffee, sum(iif(tea = 2, 1, 0)) as tea,
       sum(iif(water = 2, 1, 0)) as water, sum(iif(hot_choc = 2, 1, 0)) as hot_choc
from drinks d;

在其他数据库中有更简单的方法可以做到这一点。

于 2013-11-07T23:34:47.283 回答