将重复行设置为一行并将一个不同的列值合并

时间:2014-07-09 11:20:39

标签: sql

我有一个这样的表enter image description here

在此表中,orderID列是重复的,但其CollectDate是不同的

所以我想设置我的表AS意味着IF OrderID相同然后连接收集日期

enter image description here

我的查询正在关注及其工作

            SELECT distinct df.OrderId as OrderId,df.FileName as FileName, df.RandomKey as RandomKey,      
            df.ClientId as ClientId, df.ProjectId as ProjectId, df.Status as Status,df.UserId as UserId,       
            df.emailTo as emailTo,df.PackageType as PackageType,df.RequestedDatetime as RequestedDatetime,
            STUFF(
            (SELECT '  |  ' +  convert(varchar(10),ord.CollectDate, 101)                                                

            FROM SMXPSU.OrderDetails ord
            WHERE df.OrderId =ord.OrderId --and ord.OrderId in(getdate()-30) 
            FOR XML PATH('')),1,1,'') AS CollectDate
            FROM SMXPSU.downloadfiles  AS df                  
            INNER Join
              SMXPSU.OrderDetails ord (NOLOCK) 
            ON df.OrderId=ord.OrderId    
            WHERE df.ClientId='shaw22'  and df.PackageType='Hard Copy' and df.RequestedDatetime>=getdate()-30 
            GROUP BY df.OrderId,FileName,PackageType,RequestedDatetime,RandomKey,ClientId,ProjectId,Status,UserId,emailTo,PackageType,RequestedDatetime,CollectDate

            order by df.OrderId desc ![enter image description here][3]

但是输出给我这样的

enter image description here

表示如果CollectDate相同,然后累计多次,但我只想要一次相同的

2 个答案:

答案 0 :(得分:1)

SELECT OrderId, RandomKey, PackageType, RequestedDate, 
CASE 
WHEN COUNT(*)=1 THEN CAST(MIN(CollectDate) AS VARCHAR(20))
ELSE CAST(MIN(CollectDate) AS VARCHAR(20)) + '-' + CAST(MAX(CollectDate) AS VARCHAR    (20)) AS CollectDate
FROM
Table
GROUP BY OrderId, RandomKey, PackageType, RequestedDate

答案 1 :(得分:1)

您可以尝试以下查询

;WITH order_cte
AS
(
    SELECT OrderId,RandomKey,PackageType,RequestedDate,
    (
        SELECT CAST(CAST(orders.CollectedData AS DATE) AS VARCHAR)  + '-' AS 'text()'   
        FROM Orders WHERE Orders.OrderId=o.OrderId 
        FOR XML Path('')
    ) [CollectDate]
    FROM Orders o
    GROUP BY OrderId,RandomKey,PackageType,RequestedDate
)
SELECT OrderId,RandomKey,PackageType,RequestedDate,LEFT([CollectDate],LEN([CollectDate])-1) AS [CollectDate] 
FROM order_cte;