Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 根据发票类型从不同的表中获取员工_Sql_Sql Server - Fatal编程技术网

Sql 根据发票类型从不同的表中获取员工

Sql 根据发票类型从不同的表中获取员工,sql,sql-server,Sql,Sql Server,我有两张这样的桌子: **Invoices:** InvoiceId Type Number EmployeeId 1 A 100 -1 2 B 200 11 3 A 300 -1 4 B 400 13 **Deliveries:** DeliveryId InvoiceId EmployeeId 1 1 10 2 2

我有两张这样的桌子:

**Invoices:**
InvoiceId Type Number EmployeeId
1          A   100    -1
2          B   200    11
3          A   300    -1
4          B   400    13


**Deliveries:**
DeliveryId InvoiceId EmployeeId
1          1         10
2          2         500
3          2         501
4          3         12
5          4         502
6          4         503
发票连接到一个或多个交货。 员工是在交货或发票上签字的人

我的数据中的逻辑是: 如果只有一个交货加入发票,我们从交货中读取员工,这是类型A。如果有更多交货,我们从发票中读取员工,这是类型B

我想得到:

InvoiceId Number TrueEmployee
1         100    10
2         200    11
3         300    12
4         400    13
或者最终

InvoiceId Number InvoiceEmployee DeliveryEmployee
1         100    whatever        10
2         200    11              whatever
3         300    whatever        12
4         400    13              whatever
我试过了

Select InvoiceId,Number,Invoices.EmployeeId,Deliveries.EmployeeId
from Invoices inner join Deliveries
on Invoices.InvoiceId=Deliveries.InvoiceId
但是,如果连接了多个交货,它将为每个发票返回多行

有什么想法吗?
如果有必要的话,我使用的是Ms SQL Server。

这是一个没有分组的版本,但是有一个更具选择性的
左连接:

SELECT i.InvoiceId,
       i.Number,
       CASE i.Type WHEN 'A' THEN 999 ELSE i.EmployeeId END iEmployeeId, 
       COALESCE(d.EmployeeId,999) dEmployeeId 
FROM invoices i
LEFT JOIN deliveries d ON i.Type='A' 
                      AND d.InvoiceId = i.InvoiceId

随便挑最适合你的。
(在我的示例中,我使用了
999
作为“whatever”的值)。

谢谢!这对我来说真的很有用-只有在发票类型合适的情况下才能加入交货。再也没有双排了。