SQL根据值将一列分为两列并使用列

时间:2018-07-26 05:17:55

标签: sql sql-server

表格:ProductionOrder


Id     Ordernumber     Lotsize
1        Order1            50
2        Order 2           75
3        WO-order1         1
4        WO-order2         1

表格:history


Id          ProductionOrderID          Completed  
1            3                         1
2            3                         1
3            4                         1
4            4                         1

表格:ProductionOrderDetail


ID   ProductionOrderID     ProductionOrderDetailDefID   Content
1     1                    16                            50
2     1                    17                            7-1-2018
3     2                    16                            75
4     2                    17                            7-6-2018  

我的代码开头:


 Select p.ID, p.OrderNumber, 
     Case productionOrderDetailDefID
         Where(Select pd1.productionOrderDetailDefID where ProductionOrderDetialDefID = 16) then min(pd1.content)
 from ProductionOrder p
     Left join History h1 on  p.id = h1.productionOrderID
     Left Join ProductionOrderDetail pd1 on p.ID = ProductionOrderID

尝试获取的结果是

Id      Ordernumber     Lotsize   Productionorder        Completed
1       Order1            50           WO-order1           2
2       Order 2           75           WO-order2           2

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

尝试一下

SELECT ordernumber,lotsize,Ordernumber,count(Ordernumberid) 
       FROM productionorder inner join history on productionorder.id = history.Ordernumberid 
       GROUP BY Ordernumber;

答案 1 :(得分:1)

在这里进行一些奇怪的连接。您应该将此添加到SQL提琴,以便我们可以更轻松地看到我们的工作。

SQL小提琴的链接:http://sqlfiddle.com/

这是我的第一次尝试

SELECT
        po.id
    ,   po.ordernumber
    ,   po.lotsize 
    ,   po2.productionorder 
    ,   SUM(h.completed) 
FROM productionorder as po 
INNER JOIN history as h 
    ON h.id = po.id 
INNER JOIN prodcuctionorder as po2 
    ON po2.ordernumberid = h.ordernumberid 
WHERE po.id NOT EXISTS IN ( SELECT ordernumberid FROM history ) 
GROUP BY 
        po.id 
    ,   po.ordernumber 
    ,   po.lotzise 
    ,   po2.productionorder 

那能带你走多远?