mikepreble
mikepreble

Reputation: 269

Combine 2 select statements

I have 2 select statements and would like to combine them so they're displayed in 1 table.

Select 1:

SELECT
LAST_DAY, SUM(BILLABLE), AVG(BILLABLE)
FROM EMPLOYEES
GROUP BY YEAR(LAST_DAY),WEEK(LAST_DAY) ORDER BY LAST_DAY

Select 2:

SELECT BILLABLE 
FROM EMPLOYEES 
WHERE NAME LIKE '$lookup%'

The goal here is to show all employee's billable sum and average per week (the first select statement) and then add a column with the particular 'lookup' employee's billable amount for that week.

Both statements work fine individually, but it would be more meaningful for the employee if they could easily compare where they stand on a weekly basis vs the average.

Edit for an example:

The EMPLOYEE table looks something like this

NAME | LAST_DAY | BILLABLE
Bob   05/13/2011   18.5
Mary  05/13/2011   12.68
Steve 05/13/2011   15.2
Bob   05/06/2011   14.1
Mary  05/06/2011   11.17
Steve 05/06/2011   23.62

I want the results of the query to look something like this:
Assuming $lookup == "Bob"

LAST_DAY   | ALL_BILLABLE_TOTAL | ALL_BILLABLE_AVG | EMPLOYEE_BILLABLE_TOTAL
05/13/2011     46.38                15.46                 18.5
05/06/2011     48.89                16.29                 14.1

Upvotes: 3

Views: 1541

Answers (1)

Tom H
Tom H

Reputation: 47402

The "lookup" row thing looks like it's probably a kludge, so I'd question your design. Also, it looks like your "Employee" table isn't actually rows of employees, but rows of weekly sales or something. It doesn't seem like it's 3NF, which will probably cause you a lot of headaches. Anyway, I think that this will do what you want:

SELECT
    SQ.last_day,
    SQ.all_billable_total,
    SQ.avg_billable_total,
    LU.billable AS employee_billable_total
FROM
    (
        SELECT
            E.last_day,
            SUM(E.billable) AS all_billable_total,
            AVG(E.billable) AS avg_billable_total,
        FROM
            Employees
        WHERE
            name NOT LIKE '$lookup%'
        GROUP BY
            E.last_day
    ) SQ
LEFT OUTER JOIN Employees LU ON
    LU.name LIKE '$lookup%' AND
    LU.last_day = SQ.last_day

The join to the lookup row will cause multiple results if you have multiple rows that match the join. If this is just a row to tally that week's sales, then get rid of those rows and do something like this:

SELECT
    E.last_day,
    SUM(CASE WHEN name = @name THEN E.billable ELSE NULL END) AS all_billable_total,
    AVG(CASE WHEN name = @name THEN E.billable ELSE NULL END) AS avg_billable_total,
    SUM(E.billable) AS employee_billable_total
FROM
    Employees E
WHERE
    E.last_day IN (SELECT last_day FROM Employees WHERE name = @name)
GROUP BY
    E.last_day

You need to use the NULL in the CASE statements because using 0 will throw off the average.

Upvotes: 2

Related Questions