Mysql SQL:如何从一个列/类型中获取不同的值?
我试图从下面的姓名表中求出总数:Mysql SQL:如何从一个列/类型中获取不同的值?,mysql,sql,Mysql,Sql,我试图从下面的姓名表中求出总数: id type num 2 0 90 24 1 38 2 1 878 9 0 8763 9 2 76 9 1 374 type列中有三种类型,我想找到它们的type=0和1的所有ID。例如,在表中,id=2和id=9具有type=0和type=1。因此,我们将选取这些数据并将其添加到一起,如下所示: type: num id 2 - 0:90 1:878 i
id type num
2 0 90
24 1 38
2 1 878
9 0 8763
9 2 76
9 1 374
type
列中有三种类型,我想找到它们的type=0
和1
的所有ID。例如,在表中,id=2
和id=9
具有type=0
和type=1
。因此,我们将选取这些数据并将其添加到一起,如下所示:
type: num
id 2 - 0:90
1:878
id 9 - 0:8763
1: 374
sum = 90 + 878 + 8764 + 374 = 10,106
我是这样做的:
SELECT SUM(num) FROM table WHERE type = 0 AND type = 1;
但是没有什么可以展示的。如果我将查询更改为type=0或type=1
,它会起作用,但我认为这是不对的。如何求和num
其中type=0
和type=1
我很困惑,我不确定我是否解释清楚,如果你能提供一些帮助,我将非常感激。这应该可以做到:
select
sum(a.num + b.num)
from (
select id, num from table where type = 0
) a
join (
select id, num from table where type = 1
) b on a.id = b.id
如果我能很好地理解这个问题,答案很简单:
SELECT SUM(num)
FROM name
WHERE type = 0 OR type = 1
您希望对type=0或type=1的行中的所有num
值求和。这正是上面的SQL查询所表达的。事实上,你也来了
这就是@lily所需要的吗?这个查询:
select id from tablename
where type in (0, 1)
group by id
having min(type) = 0 and max(type) = 1
您将获得同时具有类型0和1的所有ID
因此,您可以将其加入表中,以获得所需的总数:
select sum(t.num) total
from tablename t inner join (
select id from tablename
where type in (0, 1)
group by id
having min(type) = 0 and max(type) = 1
) g on g.id = t.id
where t.type in (0, 1)
请参见
或不加入:
select sum(t.num) total from (
select id, sum(num) num from tablename
where type in (0, 1)
group by id
having min(type) = 0 and max(type) = 1
) t
请参见其中type=0和type=1的。你认为这会给你带来什么结果吗?这两个条件加在一起永远不会成立。记录不能同时为类型0和1。