简体   繁体   English

将分组应用于If语句结果

[英]Apply Group By to If Statement Results

Essentially, I have two tables: 基本上,我有两个表:
Table A 表A.

aId|isOne|bId
---+-----+---
1  |1    |2
2  |0    |2
3  |1    |1

Table B 表B.

bId|one|two
---+---+---
1  |5  |13
2  |3  |11

Table A refers to Table B and specifies whether the data of one or of two is desired. 表A引用了表B,并指定是否需要onetwo数据。 What I need to do is sum the values given the bId , so the expected result of the query on these table would be: 我需要做的是将给定bId的值bId ,因此在这些表上查询的预期结果将是:

bId|value
---+-----
2  |14
1  |5

Currently my query for doing this has the following form: 目前,我执行此操作的查询具有以下形式:

select bId, 
        coalesce(if(bId = 0, null, 
                    sum(if(isOne = 0, 
                           (select two from tableB where tableB.bId = bId),
                           (select one from tableB where tableB.bId = bId)))) as value 
from (select bId, isOne, one, two from tableA 
      join tableB on tableA.bId = tableB.bId) as tableRes;

Please note that this is in relaity part of a larger query and uses larger tables, where the coalesce and first if statement do make sense to use. 请注意,这是较大查询的相关部分,并且使用较大的表,在这里使用合并和first if语句确实有意义。

An error occurs with the above query though ( 但上述查询发生错误(

Error Code: 1242. Subquery returns more than 1 row) 错误代码:1242。子查询返回的行数超过1)

which is believed to come from the if statement within sum() . 据认为这来自sum()的if语句。 I have tried applying group by , since I think I need to group the bId = 2 value results together, but have failed to be able to place this legally, or place it legally within the query and have it actually stop the subqueries from returning more than one result. 我尝试过应用group by ,因为我认为我需要将bId = 2值结果组合在一起,但是无法合法地放置它,或者将它合法地置于查询中并让它实际上阻止子查询返回更多一个结果。 Any direction or help in fixing the error would be appreciated, also may good to know that as stated, this is a stripped down version of the query, so if it is thought the problem is not in what has been shown more can be added, but I'm pretty confident in the error lying in the above version. 我们将不胜感激地指出解决错误的任何方向或帮助,也很高兴知道,如上所述,这是查询的精简版本,因此,如果认为问题不在所显示的内容之外,则可以添加,但我对上述版本中的错误很有信心。

I would simply inner join the 2 tables and use case statement within the sum() to sum the right values: 我只需要简单地内部连接2个表,并在sum()中使用用例语句来求和正确的值:

select tableA.bId, sum(case when isOne=0 then two when isOne=1 then one else 0 end) as val
from tableA 
inner join tableB on tableA.bId = tableB.bId
group by tableA.bId ;

You don't need such a complicated structure, just do the sums in the join. 您不需要如此复杂的结构,只需在连接中求和即可。

SELECT tableA.bId, SUM(IF(isOne, one, two)) AS value
FROM tableA
JOIN tableB ON tableA.bId = tableB.bId
GROUP BY tableA.bId

实际上,对于任何对答案感到好奇的人,我都可以用指定的tableA.bId值替换子查询中的任意bId来解决此问题。

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

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