组合两个SELECT WHERE语句

时间:2016-06-14 08:47:17

标签: sql-server

我正在尝试从MS SQL Server 2014数据库中查询两个表,其中我具有只读访问权限。

需要注意的是,我需要在单个输出中组合两个类似的SELECT WHERE语句的结果:

SELECT     Item, Price, Element, Time
FROM       Goods, Goods, RoutingLine, RoutingLine    
WHERE      Goods.Routing IS NOT NULL 
AND        Goods.Routing = RoutingLine.Routing
AND        RoutingLine.Element= 'Machine%'

SELECT     Item, Price, Element, Time
FROM       Goods, Goods, RoutingLine, RoutingLine    
WHERE      Goods.Routing IS NOT NULL 
AND        Goods.Routing = RoutingLine.Routing
AND        RoutingLine.Element= 'Operator'

所需的输出应该是这样的:

Item | Price | Element (machine) | Time (machine) | Element (operator) | Time (operator)

我目前不知道如何继续,也许是临时表? 但我甚至不确定它只能用于db_reader访问。

编辑:这里要求的是一些模型表

商品

ITEM (unique) | PRICE | ROUTING
Bananas       | 12.22 | RTBanana01
Apples        | 10.00 | RTFruit01
Peaches       | 17.15 | RTPeach01
Pears         | 32.19 | RTFruit01 
Kiwi          | 02.19 | 
Cherries      |       | RTFruit02
Mangoes       |       | RTMango01
Oranges       |       |

ROUTINGLINES

ID (unique) | ROUTING    | ELEMENT    | TIME
0001        | RTBanana01 | Machine 01 | 5.12
0001        | RTBanana01 | Overhead   | 0.30
0003        | RTBanana01 | Setup      | 1.00
0004        | RTBanana01 | Operator   | 5.12
0005        | RTFruit01  | Machine 03 | 8.20        
0006        | RTFruit01  | Overhead   | 0.30  
0007        | RTFruit01  | Operator   | 4.10            
0008        | RTPeach01  | Machine 01 | 6.10      
0009        | RTPeach01  | Setup      | 1.50
0010        | RTFruit02  | Setup      | 3.50
0011        | RTMango01  | Operator   | 1.75
0012        | RTMango01  | Overhead   | 4.75

渴望输出

ITEM (unique) | PRICE | MACHINE    | MC TIME | OPERATOR | OP TIME
Bananas       | 12.22 | Machine 01 | 5.12    | Operator | 5.12
Apples        | 10.00 | Machine 03 | 8.20    | Operator | 4.10
Peaches       | 17.15 | Machine 01 | 6.10    |          |
Pears         | 32.19 | Machine 03 | 8.20    | Operator | 4.10 
Cherries      |       |            |         |          |
Mangoes       |       |            |         | Operator | 1.75     

1 个答案:

答案 0 :(得分:0)

您可以使用“AS”组合两者来识别表格。

情况的一个更简单的例子:

如果你有:

    .clearValue( 'input[id=patientId]')
    .setValue( 'input[id=patientId]', 'your_text')

SELECT     Item, Time
FROM       Goods, RoutingLine    
WHERE      Goods.Routing = RoutingLine.Routing
AND        RoutingLine.Element= 'Machine%'

你可以把它结合到:

SELECT     Item, Time
FROM       Goods, RoutingLine    
WHERE      Goods.Routing = RoutingLine.Routing
AND        RoutingLine.Element= 'Operator'

(假设Goods.Item是唯一键)