如何在SQL中创建此输出

时间:2016-10-24 11:04:15

标签: sql sql-server sql-server-2008

我有这些信息。

表OrderTotals

Order  Value
A         10
B         20
C         15

表顺序

Order  Line Description
A        11 Red
B        24 Blue
B        25 Green
B        28 Yellow
C        17 Green

我想要这个输出

Order Line Description Value
A       11 Red         10
B       24 Blue        20
B       25 Green
B       28 Yellow
C       17 Green       15

这可能吗?如果是的话,怎么样?

4 个答案:

答案 0 :(得分:3)

您似乎想要left join

select od.*,
       (case when row_number() over (partition by od.[order] order by line) = 1
             then ot.value
        end) as value
from orderdetails od left join
     ordertotals ot
     on od.[order] = ot.[order]
order by od.[order], od.line;

我不确定为什么你只想要value一行,但这应该达到这个目标。

答案 1 :(得分:1)

试试这个

SELECT A.[Order],
       CASE
         WHEN Row_number()
                OVER(
                  PARTITION BY A.[ORDER]
                  ORDER BY A.[ORDER]) = 1 THEN VALUE
         ELSE NULL
       END AS VALUE,
       B.[Line Description]
FROM   TABLE1 A
       LEFT JOIN Table2 B
              ON A.[Order] = B.[Order] 

答案 2 :(得分:0)

尝试以下查询。

            select 
            od.Order,
            od.Line ,
            od.Description,
            ot.Value

            from
            OrderTotals OT 
            join Orderdetails OD on OT.order=od.order

如果您有任何疑问,请告诉我们

答案 3 :(得分:0)

您可以如下所示:

SELECT  
    *
FROM    
    Orderdetails X LEFT JOIN
    (
        SELECT
            *
        FROM
            OrderTotals A INNER JOIN
            (SELECT OD.Order, MIN(OD.Line) MinLine FROM Orderdetails OD GROUP BY OD.Order) B ON A.Order = B.Order

    ) Y ON X.Order = Y.Order AND X.Line = Y.MinLine