问题
I'm trying to get the fields which value is not match base on the compared rows. It's hard to explain so I'll put the sample table and its results.
Table: orders
| seqid | orderId | taskId | field1 | field2 | field3 | field4 |
+---------+-----------+----------+----------+----------+----------+----------+
| 1 | 1 | 1 | a | b | c | d |
| 2 | 1 | 2 | a | b | c | d |
| 3 | 2 | 1 | a | b | c | d |
| 4 | 2 | 2 | a | c | c | c |
| 5 | 3 | 1 | a | a | a | a |
Results:
| OrderId | FieldName | Error |
+-----------+-------------+---------+
| 2 | field2 | 1 |
| 2 | field4 | 1 |
Here you can see that the orderId
will be compared using its taskId
. From field1 to field4 are the fields to be check if their values are not match. If so, then get the field name. The column Error
is not a priority, you can disregard it. If the orderId has only one task then it will not be compared.
My first plan is to use two query that will separate the taskId
then Java will do the rest. But if possible with just a query that would be great. Even though I'm not knowledgeable with stored procedure, if its the only way then let me show and I'll check on it.
I don't have any working query yet or even get a result as close to what I wanted. Any answer will be appreciate. Thanks!
UPDATED:
I guess the results is difficult to answer. I'll post another result which is I think much easy to solve.
Results2
| orderId | field1 | field2 | field3 | field4 |
+-----------+----------+---------+---------+----------+
| 1 | 0 | 0 | 0 | 0 |
| 2 | 0 | 1 | 0 | 1 |
For the second results I need to know if the field has unmatched value if yes it will display 1. The process of this results is to compare the two rows which is the Task = 1
and Task = 2
with same orderId
. I will filter the fields which have unmatched value in Java.
I hope someone here can answer it even the second results. If you can answer the first results, that would be a great help.
回答1:
SELECT
orderId,
CASE MIN(field1) WHEN MAX(field1) THEN 0 ELSE 1 END AS field1,
CASE MIN(field2) WHEN MAX(field2) THEN 0 ELSE 1 END AS field2,
...
FROM atable
GROUP BY
orderId
回答2:
Try this:
select orderid
from orders
group by orderid
having count(*) > 1
and min(field1) <> max(field1) and min(field2) <> max(field2) ...
来源:https://stackoverflow.com/questions/5698087/how-to-compare-two-rows-or-get-the-fields-which-value-is-not-match-with-the-rows