我是SQL Server的新手,刚开始玩它。我正在尝试创建一个按部门显示出勤率的表格。
首先我运行此查询:
SELECT CrewDesc, COUNT(*)
FROM database.emp
INNER JOIN database.crew on sim1 = sim2
GROUP BY CrewDesc
这给出了一个这样的表:
Accounting 10
Marketing 5
Economics 20
Engineering 5
Machinery 5
Tech Support 10
然后我再次运行查询:
SELECT DeptDescription, COUNT(*)
FROM database.Attendee
GROUP BY DeptDescription
这给了我参加会议的所有人的结果
Accounting 8
Marketing 5
Economics 15
Engineering 10
Tech Support 8
然后我按SELECT Datepart(ww, GetDate()) as CurrentWeek
获得当年的当前一周。为了让这个例子变得简单,我们假设这将是一周“2”。
现在我要创建这个的方式是每个步骤的表格,但这似乎是浪费。有没有办法可以在查询中组合表格?所以在最终的结果我想要一个像这样的表
Total# Attd Week (Total*Week) Attd/(Total*week)%
Accounting 10 8 2 20 8/20
Marketing 5 5 2 10 5/10
Economics 20 15 2 40 15/40
Engineering 5 10 2 10 10/10
Machinery 5 NULL 2 10 0/10
Tech Support 10 8 2 20 8/20
答案 0 :(得分:1)
好的,请注意,我在下面的建议是基于您确切的现有查询 - 当然还有其他方法来构建这些可能更高效的方法,但从功能上来说,这应该适合您的要求。此外,它还说明了与您的请求相关的不同连接类型的关键功能,以及内联视图(也称为嵌套查询),它们是SQL语言中的超级强大技术。
select t1.CrewDesc, t1.Total, t2.Attd, t3.Week,
(t1.Total*t3.Week) as Total_x_Week,
case when isnull(t1.Total*t3.Week, 0) = 0 then 0 else isnull(t2.Attd, 0) / isnull(t1.Total*t3.Week, 0) end as PercentageAttd
from (
SELECT CrewDesc, COUNT(*) AS Total
FROM database.emp INNER JOIN database.crew on sim1 = sim2
GROUP BY CrewDesc
) t1
left outer join /* left outer to keep all rows from t1 */ (
SELECT DeptDescription, COUNT(*) AS Attd
FROM database.Attendee GROUP BY DeptDescription
) t2
on t1.CrewDesc = t2.DeptDescription
cross join /* useful when adding a scalar value to all rows */ (
SELECT Datepart(ww, GetDate()) as Week
) t3
order by t1.CrewDesc
祝你好运!
答案 1 :(得分:0)
尝试这样的事情
SELECT COALESCE(a.crewdesc,b.deptdescription),
a.total,
b.attd,
Datepart(ww, Getdate()) AS week,
total * Datepart(ww, Getdate()),
b.attd/(a.total*Datepart(ww, Getdate()))
FROM (query 1) a
FULL OUTER JOIN (query 2) b
ON a.crewdesc = b.deptdescription
答案 2 :(得分:0)
我假设您的查询是正确的 - 您没有提供有关您的模型的真实信息,因此我无法知道。它们看起来不对,因为相同的数据在一个表中称为CrewDesc而在另一个表中称为Dept。加入sim1 = sim2对我来说似乎很奇怪。在任何情况下,如果您发布的查询都可以使用。
With TAttend as
(
SELECT CrewDesc, COUNT(*) as TotalNum
FROM database.emp
INNER JOIN database.crew on sim1 = sim2
GROUP BY CrewDesc
), Attend as
(
SELECT DeptDescription, COUNT(*) as Attd
FROM database.Attendee
GROUP BY DeptDescription
)
SELECT CrewDesc as Dept, TotalNum, ISNULL(Attd, 0) as Attd ,Datepart(ww, GetDate()) as Week,
CASE WHEN ISNULL(Attd, 0) > 0 THEN 0
ELSE ISNULL(Attd, 0) / (TotalNum * Datepart(ww, GetDate()) ) END AS Percent
FROM TAttend
LEFT JOIN Attend on CrewDesc = DeptDescription
答案 3 :(得分:0)
@Override
public void setRequestHandler(RequestHandler requestHandler) {
//store requestHandler somewhere accessible.
}