SQL - 为特定列或表选择第一个匹配的行列值和任何后续行值为null

时间:2017-08-28 19:40:12

标签: sql-server tsql

2个表格,数据如下所示。

订单表:

| OrderId | TotalAmount | TotalTax |
|---------|-------------|----------|
|    1    |    10       |    0.1   |
|    2    |    40       |    0.4   | 
|    3    |    20       |    0.2   |

项目表:(OrderId FK)

| OrderId | ItemId | ItemDesc |
|---------|--------|----------|
|    1    |    1   |   Item1  |
|    1    |    2   |   Item2  | 
|    2    |    1   |   Item1  | 
|    2    |    3   |   Item3  | 
|    2    |    5   |   Item5  | 
|    3    |    7   |   Item7  | 
|    3    |    5   |   Item5  | 

预期输出 - 连接两个表后的记录应该具有匹配第一行中记录的值,后续匹配行应该对来自订单表的列具有空值。如下图所示

| OrderId | TotalAmount | TotalTax |ItemId | ItemDesc |
|---------|-------------|----------|-------|----------|
|    1    |    10       |    0.1   |  1    |   Item1  |
|    1    |    NULL     |    NULL  |  2    |   Item2  |
|    2    |    40       |    0.4   |  1    |   Item1  |
|    2    |    NULL     |    NULL  |  3    |   Item3  |
|    2    |    NULL     |    Null  |  5    |   Item5  |
|    3    |    20       |    0.2   |  7    |   Item7  |
|    3    |    NULL     |    NULL  |  5    |   Item5  |

查询:

DECLARE @order table(orderId int, TotalAmount  int, totaltax decimal)
Insert into @order(orderId, TotalAmount,totaltax)
values 
( 1,10,0.1),
( 2,40,0.4),
( 3,20, 0.2)

DECLARE @ITEMS table(OrderId  int, ItemId  int, ItemDesc nvarchar(50))
Insert into @ITEMS(OrderId, ItemId,ItemDesc)
values 
( 1,1,'Test1'),
( 1,2,'Test2'),
( 2,1,'Test1'),
( 2,3,'Test3'),
( 2,5,'Test5'),
( 3,7,'Test7'),
( 3,5,'Test5')

 select o.*,i.* from @order o
 inner join  @ITEMS I
 on o.orderId = i.orderId

1 个答案:

答案 0 :(得分:1)

像这样:

with q as
(
 select o.orderId, o.TotalAmount, o.totaltax, i.ItemId, i.ItemDesc, 
       case when row_number() over (partition by o.orderID order by i.ItemId) = 1 then 1 else 0 end is_first
 from @order o
 inner join  @ITEMS I
   on o.orderId = i.orderId
)
select orderId, 
       case when is_first = 1 then TotalAmount else null end TotalAmount,
       case when is_first = 1 then TotalTax else null end TotalTax,
       ItemId,
       ItemDesc
from q
order by orderId, ItemId

输出

orderId     TotalAmount TotalTax                                ItemId      ItemDesc
----------- ----------- --------------------------------------- ----------- ---------
1           10          0                                       1           Test1
1           NULL        NULL                                    2           Test2
2           40          0                                       1           Test1
2           NULL        NULL                                    3           Test3
2           NULL        NULL                                    5           Test5
3           20          0                                       5           Test5
3           NULL        NULL                                    7           Test7

(7 rows affected)