English 中文(简体)
从三个表提取记录,有时不匹配的领域
原标题:Getting records from three tables with sometimes unmatching fields

我有一个应该容易回答的问题。

我有一个称为<代码>项目的表格,主要为<代码>项目Id。

下表为<代码>项目Resources和。 Id作为外国钥匙,加上用户和时间(代表指定从事项目工作的用户)的田地

附件三 (用户用于记录项目实际使用的小时用户) 项目Id作为外在钥匙和外地<代码> 用户/代码

所需要的是,我要展示<代码>项目Id,BudgetedHours ( ProjectResources table)和ActualHours(timesheettriesEn的表格);但我要列入下列情况:

  1. a 用户被分配到项目上,但没有工作(在这种情况下,预算时间应当具有价值,实际时间应为零)。

  2. a 用户没有被分配到项目上,但已经投入使用(在这种情况下,预算受益人应为零,实际受益人应具有价值)

  3. a 用户既被分配到项目上,也已经投入工作(既包括预算受益人,也具有价值)。

有些人能否将我引向T-SQL的发言,以取得这种结果?

问题回答

你们可以尝试:

SELECT p.ProjectId, 
       (CASE WHEN pr.[User] Is NULL THEN te.[User] ELSE pr.[User] END) as [User], 
       IsNull(pr.BudgetedHours, 0.0), 
       IsNull(Sum(te.ActualHours), 0.0)
FROM Project p
LEFT JOIN ProjectResources pr on p.ProjectId = pr.ProjectId
LEFT JOIN TimeSheetEntries te on p.p.ProjectId = te.ProjectId
GROUP BY p.ProjectId, te.User, pr.BudgetedHours

但我对你的外地名称等进行猜测。 因此,你们需要为自己的领域进行调整。

我认为,你之所以存在问题,是因为你想到的是,实际时间和预算时间基本上平等,因为他们被分配到该项目中。

然而,实际和预算的计算方式非常不同。 如以下例子所示,你需要使用单独的子类计算:

select coalesce(budget.ProjectId, actual.ProjectId) as ProjectId,
       budget.BudgetedHours, actual.ActualHours
from 
(
  select projectid, sum(pr.hours) as BudgetedHours
  from Projects p 
  left outer join ProjectResources pr
) budget 
full outer join
(
  select projectid, sum(tse.hours) as ActualHours
  from  Projects p 
  left outer join TimeSheetEntries tse
     on tse.ProjectId = p.ProjectId
) actual
  on budget.ProjectId = actual.ProjectId




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

难以执行 REGEXP_SUBSTR

I m 查询Oracle 10g。 我有两张表格(样本数据见下文)。 i m 试图提取一些领域

SQL Query Shortcuts

What are some cool SQL shorthands that you know of? For example, something I learned today is you can specify to group by an index: SELECT col1, col2 FROM table GROUP BY 2 This will group by col2

PHP array callback functions for cleaning output

I have an array of output from a database. I am wondering what the cleanest way to filter the values is example array Array ( [0] => Array ( [title] => title 1 ...

OracleParameter and DBNull.Value

we have a table in an Oracle Database which contains a column with the type Char(3 Byte). Now we use a parameterized sql to select some rows with a DBNull.Value and it doesn t work: OracleCommand ...

Running numbers in SQL

I have a SQL-statement like this: SELECT name FROM users WHERE deleted = 0; How can i create a result set with a running number in the first row? So the result would look like this: 1 Name_1 2 ...

How to get SQL queries for each user where env is production

I’m developing an application dedicated to generate statistical reports, I would like that user after saving their stat report they save sql queries too. To do that I wrote the following module: ...