Hope everyone is doing well.
I have the following output…
+---------+--------------+--------------+-----------+---------+----------+ | 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 | +---------+--------------+--------------+-----------+---------+----------+
What I would like to do is SUM the tx_comp column once per unique “ord_num”.
Now I cant use GROUP BY ord_num as I also do a sum on the type of tasks.
Its like I need to know what the previous ord_num was then sum if different?
Any ideas would be greatly appreciated.
Thanks.
* EDIT *
SELECT
signoff_date,
SUM(IF(prod_desc = 'run', 1, 0)) AS run,
SUM(IF(prod_desc = 'plan', 1, 0)) AS plan,
SUM(tx_comp) AS tx_comp
FROM
(
SELECT
ord_num,
signoff_date,
program_name,
prod_desc,
tx_comp,
priority
FROM
test.orders
LEFT JOIN test.tx_comp USING (ord_num)
) AS grp
Obviously not the desired output
+--------------+------+------+---------+ | signoff_date | run | plan | tx_comp | +--------------+------+------+---------+ | 2012-08-12 | 3 | 1 | 3 | +--------------+------+------+---------+
I am after…
+--------------+------+------+---------+ | signoff_date | run | plan | tx_comp | +--------------+------+------+---------+ | 2012-08-12 | 3 | 1 | 2 | +--------------+------+------+---------+
If the value of tx_comp is always 1 or zero, then we can leverage
COUNT(), which may give us more options. For instance, we can count the distinct ord_num where tx_comp is 1:Which gives me a final query of:
And there is no need for the subquery in this case. (edit: updated for your JOIN)
I have tested this with your sample data; the only dependency is on the semantic nature of tx_comp. You have been saying “SUM”, and this assumes that the value will be at most 1 (I understand it to be a boolean flag, and in a comment on another answer you mentioned MAX(tx_comp) returning 1, so I think we’re good).