Sql中的不同行

时间:2015-10-22 10:32:45

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

我有一个记录事件的表,因此可以多次记录相同的ID。我想为每个唯一的RefID返回单行,因为'Y'代替相关列中的'N'。下面是一个模拟

    DECLARE @Ref TABLE 
    (   
      RefID        INT
     , InvoiceNo    INT 
     , InvoicedDate Date
     , CustID       INT 
     , PaidOnTime   CHAR(1)
     , Paidlate     CHAR(1)
     , PaidByCash   CHAR(1) 
     , PaidByCard   CHAR(1)
    )
   INSERT INTO @Ref VALUES
   (23,50,'22-jun-2015', 11,'Y','N','Y','N')
 , (23,50,'22-jun-2015', 11,'Y','N','N','Y')
 , (27,11,'12-Aug-2015', 11,'Y','N','N','Y')
 , (27,11,'22-Aug-2015', 11,'N','Y','N','Y')
 , (45,67,'28-jun-2015', 11,'N','Y','Y','N')
 , (45,67,'28-jun-2015', 11,'N','N','N','Y')
 , (48,51,'18-jun-2015', 11,'Y','N','Y','N') 

 SELECT * FROM @Ref --would return values like so:

enter image description here

例如,23的RefID应为“23,50,22 / 06 / 2015,11,Y,N,Y,Y”

1 个答案:

答案 0 :(得分:1)

按您想要唯一的列进行分组,并使用max()获取每个组的最高值(因为Y按字母顺序高于N

SELECT RefID, InvoiceNo, InvoicedDate, CustID,
       max(PaidOnTime), max(Paidlate), max(PaidByCash), max(PaidByCard)
FROM @Ref 
GROUP BY RefID, InvoiceNo, InvoicedDate, CustID