Mysql 仅当id不同时求和列

Mysql 仅当id不同时求和列,mysql,Mysql,希望大家都做得很好 我有以下输出 +---------+--------------+--------------+-----------+---------+----------+ | ord_num | signoff_date | program_name | prod_desc | tx_comp | priority | +---------+--------------+--------------+-----------+---------+----------+ | 123456

希望大家都做得很好

我有以下输出

+---------+--------------+--------------+-----------+---------+----------+ | ord_num | signoff_date | program_name | prod_desc | tx_comp | priority | +---------+--------------+--------------+-----------+---------+----------+ | 1234567 | 2012-08-12 | ilearn | run | 1 | 1 | | 1234567 | 2012-08-12 | ilearn | plan | 1 | 1 | | 1234568 | 2012-08-12 | other | run | 1 | 1 | | 1234569 | 2012-08-12 | other | run | 0 | 1 | +---------+--------------+--------------+-----------+---------+----------+ 显然不是期望的输出

+--------------+------+------+---------+ | signoff_date | run | plan | tx_comp | +--------------+------+------+---------+ | 2012-08-12 | 3 | 1 | 3 | +--------------+------+------+---------+ +--------------+------+------+---------+ |签署日期|运行|计划|德克萨斯州公司| +--------------+------+------+---------+ | 2012-08-12 | 3 | 1 | 3 | +--------------+------+------+---------+ 我在找

+--------------+------+------+---------+ | signoff_date | run | plan | tx_comp | +--------------+------+------+---------+ | 2012-08-12 | 3 | 1 | 2 | +--------------+------+------+---------+ +--------------+------+------+---------+ |签署日期|运行|计划|德克萨斯州公司| +--------------+------+------+---------+ | 2012-08-12 | 3 | 1 | 2 | +--------------+------+------+---------+
可能只是使用
MAX
而不是
tx\u comp
列上的
SUM
?我不确定数据的语义,但我猜这就是您想要的。事实上,
run
plan
也可能是相同的


就这点而言,您真正想要的是
BIT\u或
,因为您正在处理布尔值。

如果tx\u comp的值始终为1或零,那么我们可以利用
COUNT()
,这可能会给我们更多的选择。例如,我们可以计算不同的ord_num,其中tx_comp为1:

COUNT(distinct IF(tx_comp, ord_num, NULL))
这给了我最后一个问题:

SELECT signoff_date,
  SUM(IF(prod_desc = 'run', 1, 0)) AS run,
  SUM(IF(prod_desc = 'plan', 1, 0)) AS plan,
  COUNT(distinct IF(tx_comp, ord_num, NULL)) as tx_comp
FROM 
  test.orders
  JOIN test.tx_comp USING (ord_num)
  GROUP BY signoff_date
在这种情况下,不需要子查询。(编辑:为您的加入更新)


我已经用你的样本数据对此进行了测试;唯一的依赖性在于tx_comp的语义性质。您一直在说“SUM”,这假设值最多为1(我理解它是一个布尔标志,并且在对另一个答案的评论中您提到MAX(tx_comp)返回1,所以我认为我们很好)。

那么您希望在一个查询中使用两个不同条件的不同的和?@MarcB yes这是正确的。。。“只有在ord_num不同的情况下”-与什么?上一行?@KeithRandall我只想对每个唯一的“ord_num”对“tx_comp”列求和一次。如果我不清楚,我表示歉意。tx_comp总是1还是零?您想要求和还是非零的计数?请注意,第二个问题只有在第一个答案是“不,不总是”时才重要“感谢您的回复,max不起作用,因为它只为tx_comp提供了1的输出。如果tx_comp不同,请说tx_comp=1、2、3等,并希望求和而不是计数。
SELECT signoff_date,
  SUM(IF(prod_desc = 'run', 1, 0)) AS run,
  SUM(IF(prod_desc = 'plan', 1, 0)) AS plan,
  COUNT(distinct IF(tx_comp, ord_num, NULL)) as tx_comp
FROM 
  test.orders
  JOIN test.tx_comp USING (ord_num)
  GROUP BY signoff_date