Two records that have same data cell value in one field but different in another, query to return only one based on criteria

StackOverflow https://stackoverflow.com/questions/13499259

문제

I need some help on my mysql syntax.

My table has user information but has the same order number for both ship to and bill to.

Sometimes people choose to ship to their billing address; I only need the order number record where users didn't enter a shipping addresses, and where they entered a shipping address.

If they entered both bill to and shipping addresses, I only need the shipping address, if that makes sense.

In the table there are sometimes duplicate fields for one order number. If that's confusing take a look below:

------------SQL TABLE ----------- 
order_id | address_type | user_name       | address
100      | billto       | Homer Simposn   | 123 Main St.
100      | shipto       | Homer Simpson   | 455 XYZ Ave. 
101      | billto       | Peter Griffin   | 780 111th St.
102      | billto       | Charles Xavier  | 555 Bergen St.
102      | shipto       | Jean Gray       | 555 Bergen St.

I need the output to be:

100 - shipto - Homer Simposn - 455 XYZ Ave. 
101 - billto - Peter Griffin - 780 111th St.
102 - shipto - Jean Gray - 555 Bergen St.

Here is my syntax which will only return "shipto" records.

    SELECT * FROM order_info AS A WHERE A.address_type = 'shipto' AND 
NOT EXISTS (SELECT B.address_type 
                    from order_info AS B 
                    where B.address_type = A.address_type 
                    and B.address_type = 'billto')

I would like to do something like IF there is no shipto then return the billto, Is this possible to do all in sql syntax?

Thanks!

도움이 되었습니까?

해결책

You could achieve this by finding the groupwise maximum for your row.

Specifically, you use the order as the ID, and find the "maximum" address type in a subquery (it will find shipto if it's there, and billto if not), and use that result to connect to rows in the outer query.

For example (using an inefficient correlated subquery):

SELECT * FROM order_info AS A WHERE A.address_type = (
   SELECT MAX(address_type) FROM order_info AS B 
   WHERE A.order_id = B.order_id )

The above link gives an example of converting that to a more efficient join.

다른 팁

select * from test
where address_type = "shipto"
union
select * from test t1
where address_type = "billto"
and (select count(*) from test t2 where t2.order_id = t1.order_id group by order_id) = 1;

I am not sure how efficient it is but it gets your result for sure. You can match up the performance with the other ways you find.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top