查询显示为单行的多个记录

时间:2015-03-30 06:13:05

标签: sql sql-server

我有一个表,表包含大量具有申请人唯一号码的记录,

SINo , ApplUniqNo, Amount, PaymentId,Year
1,         203,   2583.02,   1,   2014-15
2,         307,   1254.25,   2,   2014-15
3,         203,   2413.50,   2,   2014-15
4,         203,   5689.32,   1,   2014-15

上表显示相同记录ApplUniqNo:203, 我的要求就像这样显示

ApplUniqNo,Amount,PaymentId
203, 2583.02/2413.50/5689.32 ,1/2/1
你可以帮助我吗?写一个程序查询。

1 个答案:

答案 0 :(得分:0)

您可以将FOR XML用于此

;WITH CTE AS
(
SELECT
     ApplUniqNo
    ,(SELECT 
        CONVERT(VARCHAR,Amount)+'/' from @TempTable Amounts WHERE Amounts.ApplUniqNo = YourTable.ApplUniqNo
        FOR XML PATH('')   )  AS Amount
 ,(SELECT 
  CONVERT(VARCHAR,PaymentId)+'/' from @TempTable PaymentIds WHERE PaymentIds.ApplUniqNo = YourTable.ApplUniqNo
    FOR XML PATH(''))  AS PaymentID
FROM
    YourTable
)

SELECT
    ApplUniqNo
    ,SUBSTRING(Amount,0,LEN(Amount)) AS Amount
    ,SUBSTRING(PaymentID,0,LEN(PaymentID)) AS PaymentID
FROM 
    CTE

公用表表达式用于删除最后一个额外的' /'使用子字符串