我有2个选择语句,并希望将它们组合起来,以便它们显示在1个表中。
选择1:
SELECT
LAST_DAY, SUM(BILLABLE), AVG(BILLABLE)
FROM EMPLOYEES
GROUP BY YEAR(LAST_DAY),WEEK(LAST_DAY) ORDER BY LAST_DAY
选择2:
SELECT BILLABLE
FROM EMPLOYEES
WHERE NAME LIKE '$lookup%'
此处的目标是显示所有员工的可结算金额和每周平均值(第一个选择语句),然后添加一个列,其中包含该周特定“查询”员工的可结算金额。
这两种陈述都可以单独运作,但如果员工能够轻松地比较每周的平均值与平均值相比,那么这对于员工来说会更有意义。
编辑示例:
EMPLOYEE表看起来像这样
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
我希望查询的结果看起来像这样:
假设$ 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
答案 0 :(得分:2)
“查找”行看起来像是一块垃圾,所以我会质疑你的设计。此外,看起来您的“员工”表实际上不是员工行,而是每周销售额等等。它似乎不是3NF,这可能会让你头疼。无论如何,我认为这会做你想做的事情:
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
如果有多个匹配连接的行,则连接到查找行将导致多个结果。如果这只是一周来计算那周的销售额,那么就去除那些行并做这样的事情:
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
你需要在CASE语句中使用NULL,因为使用0会抛弃平均值。