根据3列选择第一行/事务

时间:2013-11-11 01:24:20

标签: sql sql-server

我需要一个查询来为每个人和每个小组返回每个人的第一行。我还需要按小组计算。

示例数据

 evnt_dat, evnt_descrp, panel_descrp, lname, fname, cardno
 10/2/2013 8:30 AM  Local Grant Austin Panel    Evans   Michael 52836                           
 10/2/2013 8:53 AM  Local Grant Austin Panel    Lang    Richard 50385                           
 10/2/2013 8:59 AM  Local Grant Austin Panel    Evans   Michael 52836                                                   
 10/2/2013 9:22 AM  Local Grant Austin Panel    Brozek  Kerry   50346                           
 10/2/2013 9:34 AM  Local Grant Austin Panel    Brozek  Kerry   50346                           
 10/2/2013 10:02 AM Local Grant Austin Panel    Evans   Michael 52836                           
 10/3/2013 7:13 AM  Local Grant Bellevue Panel  Goins   Joseph  21082                           
 10/3/2013 7:13 AM  Local Grant Bellevue Panel  Goins   Joseph  21082                           
 10/3/2013 7:19 AM  Local Grant Bellevue Panel  Bartolovic  Doug    44974                           
 10/3/2013 7:23 AM  Local Grant Bellevue Panel  Bartolovic  Doug    44974                           

期望的结果:

10/2/2013 8:30 AM   Local Grant Austin Panel    Evans   Michael   52836  
10/2/2013 8:53 AM   Local Grant Austin Panel    Lang    Richard 50385     
10/2/2013 9:22 AM   Local Grant Austin Panel    Brozek  Kerry   50346  
count = 3  
10/3/2013 7:13 AM   Local Grant Bellevue Panel  Goins   Joseph  21082  
10/3/2013 7:19 AM   Local Grant Bellevue Panel  Bartolovic  Doug    44974  
count = 2    

我试过

;WITH CTE AS 
( SELECT *, ROW_NUMBER() OVER(PARTITION BY cardno ORDER BY convert(date,evnt_dat) DESC) AS RN 
    FROM ev_log ) 
SELECT cardno, lName, fname, evnt_Dat, panel_descrp 
  FROM CTE WHERE RN = 1

由于

1 个答案:

答案 0 :(得分:0)

<强>更新:

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, evnt_dat)) evnt_dat, 
       evnt_descrp, panel_descrp, lname, fname, cardno
  FROM
(
  SELECT evnt_dat, evnt_descrp, panel_descrp, lname, fname, cardno,
         ROW_NUMBER() OVER (PARTITION BY evnt_descrp, panel_descrp, lname, fname, 
                            DATEADD(dd, 0, DATEDIFF(dd, 0, evnt_dat)) ORDER BY evnt_dat) rnum
    FROM ev_log
) q
 WHERE rnum = 1
 ORDER BY evnt_dat, evnt_descrp, panel_descrp, lname, fname;

注意: 显然,如果你更喜欢它,你可以使用CTE代替内部选择

示例输出:

|   EVNT_DAT | EVNT_DESCRP |   PANEL_DESCRP |      LNAME |   FNAME | CARDNO |
|------------|-------------|----------------|------------|---------|--------|
| 2013-10-02 | Local Grant |   Austin Panel |     Brozek |   Kerry |  50346 |
| 2013-10-02 | Local Grant |   Austin Panel |      Evans | Michael |  52836 |
| 2013-10-02 | Local Grant |   Austin Panel |       Lang | Richard |  50385 |
| 2013-10-03 | Local Grant | Bellevue Panel | Bartolovic |    Doug |  44974 |
| 2013-10-03 | Local Grant | Bellevue Panel |      Goins |  Joseph |  21082 |

这是 SQLFiddle 演示