views:

26

answers:

2

Both of these work individually

SELECT  PONumber, 
        count(RequestNumber) as "InNumOfRequests", 
        sum(Amount) as "SumofAmounts" 
FROM tableView
GROUP BY PONumber  

SELECT DISTINCT PONumber, 
                (10 * ceiling((DATEDIFF(day,POApprovedDate,GETDATE()))/10)) 
                  AS "BINofDaysSincePOApproved"                      
FROM tableView

And I want to end up with:

PONumber   |  InNumOfRequests  |  SumofAmounts  |  BINofDaysSincePOApproved  
PO1        |  2                |  100           |  180
PO2        |  1                |  50            |  179   

tableView looks like:

RequestNumber | PONumber | Amount  |  POApproved Date   
1             | PO1      | 100.00  |  2010-01-01  
2             | PO1      | 100.00  |  2010-01-01  
3             | PO2      |  50.00  |  2010-01-02

note that PO1 is actually the PO for 2 requests and so the POApproved Data and Amount is the same for those 2 requests.

It seems easy but from the book I'm using (The Language of SQL) i can't figure it out.
Help :(
Alex

A: 

Hello!

SELECT *
   FROM (
         SELECT PONumber, count(RequestNumber) as "InNumOfRequests", sum(Amount) as "SumofAmounts"
           FROM tableView
          GROUP BY PONumber
        ) a,
        (
         SELECT DISTINCT PONumber, (10 * ceiling((DATEDIFF(day, POApprovedDate, GETDATE()))/10)) AS "BINofDaysSincePOApproved"
           FROM tableView
        ) b
 WHERE a.PONumber = b.PONumber
Benoit
Hi Benoit, I get a syntax error at the JOIN. (and MS SQL Studio doesn't see it as a keyword (it's light gray instead of blue))
Alex
Hello, I edited the request. Could you try with this syntax?
Benoit
Sweet!! and the ') a' and ') b' I guess is short for ') AS a' and ') AS b'. It seems obvious now that you show it like that but I've not seen in the \examples in my book or the google searches where you give a name to the output of a subquery... Very Cool. Thanks!
Alex
Yes, the `AS` keyword is optional.
Benoit
A: 

If the date is ALWAYS equal to each PONumber, can be put in the first select. The MIN function (MIN(POApprovedDate)) is why a group by, then should use aggregate functions in the fields.

SELECT  PONumber, 
        count(RequestNumber) as "InNumOfRequests", 
        sum(Amount) as "SumofAmounts",
        (10 * ceiling((DATEDIFF(day,MIN(POApprovedDate),GETDATE()))/10)) 
         AS "BINofDaysSincePOApproved" 
FROM tableView
GROUP BY PONumber