查询以从先前的行收集数据

时间:2010-06-24 06:55:21

标签: sql-server sql-server-2005

我有一张记录表,在下面的示例数据中,CO.Nr是TH-123,Th-456等......我需要收集数据..

Nr.       CO.Nr           Employee       Resp            Description       Date

1         TH-123          ABC            NULL              HELLO           10.05.2010
2         TH-123          NULL           S14               NULL            18.05.2010
3         TH-123          DEF                              NULL            13.05.2010
4         TH-456          XYZ            NULL              NULL             1.07.2010
5         TH-456          NULL           S19               SOME             NULL
6         TH-456                                           TEXT            08.05.2010
7         TH-456                        NULL                               28.05.2010

对于TH-123, 如果是是最大的,这是我需要以CO.Nr开始分组的记录,所以它是Nr为3的记录, 如果其他列中的值为NULL或空格,请转到上面的记录,即Nr为2的记录,即使它具有空值,也会转到该记录上方的记录,并使用Nr。在这种情况下为1。 在3条记录中,我需要采取最大日期。 对于上面的数据,我需要输出as,

      CO.Nr           Employee       Resp            Description       Date

      TH-123          DEF            S14               HELLO            18.05.2010
      TH-456          XYZ            S19               TEXT             01.07.2010

提前致谢!

2 个答案:

答案 0 :(得分:0)

您可以使用子选择选择所需的记录,然后加入该记录。对于员工一个类似于以下内容(我将其余的列留作练习):

SELECT MyTable.[CO.Nr], Employees.Employee
FROM MyTable
LEFT OUTER JOIN (SELECT FIRST(Employee) as Employee, [CO.Nr]
                 FROM MyTable
                 WHERE Employee IS NOT NULL AND Employee <> ''
                 GROUP BY [CO.Nr]
                 ORDER BY [Nr.] DESC) Employees 
           ON MyTable.[CO.Nr] = Employees.[CO.Nr]
GROUP BY MyTable.[CO.Nr]

或者,如果FIRST()不是有效的聚合函数,如评论中所述,您可以在SELECT子句中尝试子选择,例如:

SELECT t.MyTable.[CO.Nr], 
       (SELECT TOP(1) x.Employee
        FROM MyTable x
        WHERE x.[CO.Nr] = t.[CO.Nr]
        AND x.Employee IS NOT NULL AND x.Employee <> ''
        ORDER BY [Nr.] DESC) as Employee
FROM MyTable t
GROUP BY t.[CO.Nr]

答案 1 :(得分:0)

你可以采取多种方式

select [co.nr],
(select top(1) employee from mytable b where b.[co.nr]=a.[co.nr]  and 
                        employee is not null order by nr desc) as employee,
(select top(1) resp from mytable b where b.[co.nr]=a.[co.nr]  and 
                        resp is not null order by nr desc) as resp,
(select top(1) description from mytable b where b.[co.nr]=a.[co.nr]  and 
                        description is not null order by nr desc) as description,
(select max([date]) from mytable b  where b.[co.nr]=a.[co.nr]) as Date
from (
select distinct [co.nr] 
 from mytable ) as a