Question

I have a query that is working. However, it is only by ordered by company name, not by date of inside invoices of these companies:

SELECT C.FULLNAME,C.COMPANY_ID,I.INVOICE_DATE FROM COMPANY C
        JOIN #dsn2_alias#.INVOICE I ON I.COMPANY_ID = C.COMPANY_ID
        WHERE I.INVOICE_ID IS NOT NULL AND I.INVOICE_DATE <= #attributes.date# 
        AND C.COMPANY_ID NOT IN ( 
            SELECT C.COMPANY_ID FROM COMPANY C JOIN #dsn2_alias#.INVOICE I ON I.COMPANY_ID = C.COMPANY_ID WHERE I.INVOICE_ID IS NOT NULL AND I.INVOICE_DATE >= #attributes.date# 
        )
        GROUP BY C.COMPANY_ID,C.FULLNAME,I.INVOICE_DATE ORDER BY C.FULLNAME

and output:

<cfoutput query="get_companies" group="company_id">
            <tr height="20" onMouseOver="this.className='color-light';" onMouseOut="this.className='color-row';" class="color-row">
                <td style="text-align:center;">#row#</td>
                <td style="text-align:center;">#dateformat(INVOICE_DATE,'dd/mm/yyyy')#</td>
                <td>#fullname#</td>
            </tr>
            <cfset row++/>
        </cfoutput>

Actually the group by clause doesn't work from the query. It is grouped in the cfoutput.

Anyway, there is a list of companies. Each company has multiple sales (invoices). I want to list the companies that didn't have sales for a certain period of time. I have achieved it but have a little problem. I cant order them by time. I understand the mistake here, since there are multiple invoices, the companies are repeated each time, and can't be ordered by time. However, if they are ordered, it is done by invoice date thus companies are repeated. But all I want to see is the list of companies with its LAST SALE DATE time. Not repeated each time it has a sale. Hope I was clear :)

Thank you for the help!

Was it helpful?

Solution

Ok, I solved by myself by using the strawberry's hint about GROUPWISE-MAXIMUM:

SELECT C.FULLNAME,C.COMPANY_ID,I.INVOICE_DATE 
FROM   COMPANY C INNER JOIN 
            ( 
               SELECT I.COMPANY_ID,MAX(I.INVOICE_DATE) AS INVOICE_DATE 
               FROM   #dsn2_alias#.INVOICE I GROUP BY I.COMPANY_ID
            )  
            I  ON I.COMPANY_ID = C.COMPANY_ID

WHERE   I.INVOICE_DATE <= #attributes.date# 
AND     C.COMPANY_ID NOT IN 
        ( 
            SELECT C.COMPANY_ID 
            FROM   COMPANY C JOIN #dsn2_alias#.INVOICE I  ON I.COMPANY_ID = C.COMPANY_ID 
            WHERE  I.INVOICE_ID IS NOT NULL 
            AND    I.INVOICE_DATE >= #attributes.date# 
        )
GROUP BY C.COMPANY_ID,C.FULLNAME,I.INVOICE_DATE ORDER BY I.INVOICE_DATE

Now it is ordered by time and doesn't repeat companies :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top