Avatar of holemania
holemania
 asked on

SQL Query - Max Value

I need help with a query.  I have a nested query that pull from 2 tables with a union all.  I want to combine the 2 record it pull, but the greater value of the 2 into 1 record.  Or more like if it's NULL then use the other value from the other record.

See my query and example output.
SELECT 	X.ID, X.ORDER_ID, X.DATE, X.STATUS, X.ORDER_POLICY
FROM	(
	SELECT 	ITEM_ID AS ID, ORDER_ID, TRANSACTION_DATE AS DATE, NULL AS STATUS, AS NULL ORDER_POLICY
	FROM	SALES_ORDER
	WHERE	
	UNION ALL
	SELECT	ID, NULL AS ORDER_ID, NULL AS DATE, NULL AS STATUS, ORDER_POLICY
	FROM	ITEMS
	) X
WHERE	X.ID = '129892' AND ISNULL(NULLIF(X.ORDER_ID, ''), '' = 'SO12342'

Open in new window

output-sample.jpg
SQL

Avatar of undefined
Last Comment
Sean Stuber

8/22/2022 - Mon
Sean Stuber

SELECT   x.id, MAX(x.order_id), MAX(x.date), MAX(x.status), MAX(x.order_policy)
    FROM (SELECT item_id AS id,
                 order_id,
                 transaction_date AS date,
                 NULL AS status,
                 NULL AS order_policy
            FROM sales_order
            where
          UNION ALL
          SELECT id, NULL AS order_id, NULL AS date, NULL AS status, order_policy FROM items) x
GROUP BY id
  HAVING x.id = '129892' AND x.order_id = 'SO12342'
ASKER CERTIFIED SOLUTION
Sean Stuber

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Your help has saved me hundreds of hours of internet surfing.
fblack61