仅从重复行中选择不同的值

时间:2011-03-17 18:08:10

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

我有一张包含以下数据的表格:

client   totalA     totalB   item#
clientA 454265.08   869.5   307-1-3138
clientA 1110067.09  869.5   307-1-3138
clientB 15900       852.5   307-1-3149
clientC 436450.76   465     307-5-680
clientC 1066535.03  465     307-5-680

请注意,clientA和clientC有2行,因为totalA列不同 - 因为金额以2种货币显示 - 。我需要返回的是每个货币2行,但第二行应该只显示totalA列,其余为空白。所以我想要的是:

  client   totalA      totalB   item#
clientA 454265.08    869.5    307-1-3138
           1110067.09                  
clientB 15900        852.5    307-1-3149
clientC 436450.76    465      307-5-680
           1066535.03                         

有关如何在SQL Server 2008中执行此操作的任何建议吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

SELECT Client, totalA, case when number = 1 then totalb else null end totalB, case when number = 1 then item else null end Item 
FROM (
    select *, row_number() over(partition by client order by client) number 
    from Clients 
) A

答案 1 :(得分:1)

我认为你的数据没有正确规范化 - 但可能有原因。

在SQL Server 2005及更高版本上,您可以使用CTE获得接近您所需要的结果 - 试试这个:

WITH ShowClients AS
(
    SELECT 
        Client, TotalA, TotalB, ItemNo,
        ROW_NUMBER() OVER(PARTITION BY Client ORDER BY TotalA DESC) AS 'RowNo',
        ROW_NUMBER() OVER(ORDER BY Client,TotalA DESC) AS 'Sequence'
    FROM clients
)
SELECT
    Client, TotalA, TotalB, ItemNo, Sequence
FROM    
    ShowClients
WHERE
    RowNo = 1
UNION
SELECT
    '', TotalA, NULL, NULL, Sequence
FROM    
    ShowClients
WHERE
    RowNo > 1
ORDER BY
    Sequence

它给了我一个输出:

Client      TotalA        TotalB      ItemNo       Sequence
clientA     1110067.0900   869.5000   307-1-3138       1
             454265.0800   NULL       NULL             2
clientB       15900.0000   852.5000   307-1-3149       3
clientC     1066535.0300   465.0000   307-5-680        4
             436450.7600   NULL       NULL             5