我正在处理需要检索的报告
所有这些都被部门分开(新营销,新销售等)。
总共会有大约23列..
我通过使用更新填充每个字段来使用临时表。这是我正在做的简化示例。 Employee表具有所需的大部分值(hiredate,termdate等)。实际上每个更新都有一个连接,还有一些更多的条件。
update #tmptbl
set MtdHiresSales = select count(empid) from emp e where e.dept = 012
and hiredate between start_of_month() and getdate()
-- more predicates
set MtdHiresMkting = ...repeat... with e.dept=013
我确信有更好的方法,因为有很多代码重复。在这种情况下临时表是否合适?我不确定没有一个怎么办。有什么建议吗?
答案 0 :(得分:3)
您可以使用CASE
。例如:
SELECT
SUM(CASE WHEN e.dept=012
AND Hiredate between Start_of_Month() and Getdate()
AND...
THEN 1 ELSE 0 END) AS 'MtdHiresSales',
...
FROM ...
WHERE ...
答案 1 :(得分:2)
您可以使用公用表表达式来封装员工计数代码...
WITH
employee_counts
AS
(
SELECT
dept AS "dept",
x AS "x",
COUNT(empid) AS "employees"
FROM
emp
WHERE
hiredate BETWEEN start_of_month() AND getdate()
-- etc, etc
GROUP BY
dept,
x
)
UPDATE
myTable
SET
MtdHiresSales = (SELECT employees FROM employee_counts WHERE dept = 012 AND x = myTable.y),
MtdHiresMkting = (SELECT employees FROM employee_counts WHERE dept = 013 AND x = myTable.y)
答案 2 :(得分:0)
也许我很困惑或没有看到什么,但为什么不只是使用聚合?
SELECT count(*) as employeesPerDept, deptId
from mudkips
group by deptId
给(我的样本数据)
employeesPerDept deptId
6 100
4 200
和
select deptId, count(*) as empsHired, month(hiredate) as monthHired,
year(hireDate) as yearHired
from mudkips
group by deptId, month(hireDate), year(hireDate)
然后是
deptId empsHired monthHired yearHired
100 4 1 2010
100 1 1 2011
100 1 2 2010
200 2 1 2010
200 1 2 2010
200 1 3 2010