Error message after querying this statement. Please help correct. Thanks!!

Molly 1 Reputation point
2021-09-24T15:42:57.647+00:00

SELECT PO.VENDOR_ID, V.NAME from VENDOR, MAX(PO.ORDER_DATE)

PURCHASE_ORDER LEFT OUTER JOIN PURCHASE_ORDER PO ON V.ID = PO.VENDOR_ID

WHERE EXISTS (SELECT V.ACTIVE_FLAG FROM VENDOR V WHERE V.ID = PO.VENDOR_ID and V.ACTIVE_FLAG = 'Y')

GROUP BY PO.VENDOR_ID

HAVING MAX(PO.ORDER_DATE) < '01-JAN-2020'

Error:

Msg 208, Level 16, State 1, Line 1

Invalid object name 'MAX'.

Also, we actually want to extract the vendor not being active within 365 days. not the exact date as "01-JAN-2020". Please help correct too. Thanks!!

SQL Server Reporting Services
SQL Server Reporting Services
A SQL Server technology that supports the creation, management, and delivery of both traditional, paper-oriented reports and interactive, web-based reports.
2,790 questions
SQL Server Analysis Services
SQL Server Analysis Services
A Microsoft online analytical data engine used in decision support and business analytics, providing the analytical data for business reports and client applications such as Power BI, Excel, Reporting Services reports, and other data visualization tools.
1,242 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,547 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Tom Cooper 8,466 Reputation points
    2021-09-24T16:15:08.12+00:00

    I assume VENDOR.ID is the primary key of the VENDOR table. If so, I believe you want

    SELECT V.ID, V.NAME, MAX(PO.ORDER_DATE)
    FROM VENDOR V LEFT JOIN PURCHASE_ORDER PO ON V.ID = PO.VENDOR_ID
    WHERE V.ACTIVE_FLAG = 'Y'
    GROUP BY V.ID, V.NAME
    HAVING DATEDIFF(day, MAX(ISNULL(PO.ORDER_DATE, '19000101')), GETDATE()) > 365;
    

    Tom


  2. EchoLiu-MSFT 14,571 Reputation points
    2021-09-27T07:31:01.597+00:00

    Hi @Molly ,

    Welcome to the microsoft TSQL Q&A forum!

    Please try:

    SELECT PO.VENDOR_ID,V.NAME,MAX(PO.ORDER_DATE)  
    from VENDOR V.  
    LEFT OUTER JOIN PURCHASE_ORDER PO ON V.ID = PO.VENDOR_ID  
    WHERE  V.ACTIVE_FLAG = 'Y')  
    GROUP BY PO.VENDOR_ID, V.NAME   
    HAVING DATEDIFF(dd,MIN(PO.ORDER_DATE),MAX(PO.ORDER_DATE))>365  
    

    If this does not solve your problem,please share us your table structure (CREATE TABLE …) and some sample data(INSERT INTO …)
    along with your expected result? So that we’ll get a right direction and make some test.

    If you have any question, please feel free to let me know.
    If the response is helpful, please click "Accept Answer" and upvote it.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.