简体   繁体   English

SQL选择总和条件2表?

[英]sql select sum with condition 2 tables?

I have 2 table 我有2张桌子

Table Connection
----------------------------------------
|  ID       |  Member_ID  |  Connection| 
----------------------------------------
|  1        |  100        |  22        | 
----------------------------------------
|  2        |  101        |  15        | 
----------------------------------------
|  3        |  102        |  19        | 
----------------------------------------
|  4        |  103        |  21        | 

Table Member
---------------------------
|  ID         |  Status     |
---------------------------
|  100        |  0          | 
----------------------------
|  101        |  1          | 
----------------------------
|  102        |  1          | 
---------------------------
|  103        |  0          |   

I want to get sum of Connection has status =1 . 我想获取Connection status =1总和。 The result in example should be 15+19 = 34 . 示例中的结果应为15+19 = 34

Here is an example of how to write this query using generic SQL: 这是一个如何使用通用SQL编写此查询的示例:

SELECT
    SUM(Connection.Connection) AS ConnectionSum
FROM
    Connection
JOIN
    Member ON Connection.Member_ID = Member.ID
WHERE
    Member.Status = 1;

This should work fine for you : 这应该适合您:

select sum(Connection) as Total_connection 
        from Connection where ID in 
( select ID from member where status = 1 );

This is in reference to MySQL and MariaDB databases: 这是参考MySQL和MariaDB数据库:

SELECT SUM(Connection) 
       FROM Connection 
       WHERE Member_ID = ALL (SELECT ID FROM Member WHERE Status = 1);

OR 要么

SELECT SUM(Connection) 
       FROM Connection 
       WHERE Member_ID IN (SELECT ID FROM Member WHERE Status = 1);

SELECT SUM(cn. connection ) sumresult FROM connection AS cn WHERE cn. SELECT SUM(CN。 connection )sumresult FROM connection AS CN其中cn。 member_id
IN (SELECT em.id FROM member AS em WHERE em. status =1); IN(从member AS中选择​​em.id,在em中,em。 status = 1);

I hope it can help you as your require 希望它可以帮助您

You are getting an error because the subquery returns more than one ID(multiple records) where as an equal operator can take only one value. 由于子查询返回多个ID(多条记录),而作为相等的运算符只能采用一个值,因此您会收到错误消息。 Use an IN operator instead of Equal operator and your error will be removed. 使用IN运算符而不是Equal运算符,您的错误将被消除。

select sum(connection) from connection 
where connection.member_id IN (select id from member where status=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM