Solved

SQL Query - Case Statement with Null use Max

Posted on 2014-10-13
2
174 Views
Last Modified: 2014-10-13
I have 2 tables, "Payable" and "Payable_Line" which contains detail information.  I want a query to use max if one of the field in my query is "Null".  However, I can't get it to work correctly.

Query output result:
Payble and Payable_line
SELECT P.VOUCHER_ID, P.INVOICE_ID, P.TOTAL_AMT,
              CASE WHEN PL.PO_ID IS NULL THEN MAX(PL.PO_ID) ELSE PL.PO_ID END PO_ID
FROM PAYABLE P LEFT OUTER JOIN PAYABLE_LINE PL
              ON P.VOUCHER_ID = PL.VOUCHER_ID
GROUP BY P.VOUCHER_ID, P.INVOICE_ID, P.TOTAL_AMT, PL.PO_ID

Am I doing something wrong?  Basically wanting to input my max value in the "Null" field for PO_ID.
0
Comment
Question by:holemania
2 Comments
 
LVL 73

Accepted Solution

by:
sdstuber earned 500 total points
ID: 40377557
If you want both rows returned, then try an analytic instead of aggregate

SELECT p.voucher_id,
       p.invoice_id,
       p.total_amt,
       CASE
           WHEN pl.po_id IS NULL
           THEN
               MAX(pl.po_id) OVER (PARTITION BY p.voucher_id, p.invoice_id, p.total_amt)
           ELSE
               pl.po_id
       END
           po_id
  FROM payable p LEFT OUTER JOIN payable_line pl ON p.voucher_id = pl.voucher_id
0
 

Author Closing Comment

by:holemania
ID: 40377588
Awesome.  That's what I was looking for.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction: When running hybrid database environments, you often need to query some data from a remote db of any type, while being connected to your MS SQL Server database. Problems start when you try to combine that with some "user input" pass…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now