向sql查询添加更多数据列

时间:2013-11-07 23:59:37

标签: sql

如何在表格中添加更多可用的数据列?我想添加evnt_datevnt_desrp列。

SELECT DISTINCT 
        ROW_NUMBER() OVER (ORDER BY 
                                panel_descrp   
                            ,   cardno
                            ,   lname
                           ) rid 
    ,   panel_descrp   
    ,   cardno   
    ,   lname

FROM ev_log

where evnt_descrp = 'local grant' 
      and datepart(yyyy,EVNT_DAT) = datepart(yyyy,GETDATE()) 
      and DATEPART(mm,evnt_dat)   = DATEPART(mm,getdate()) -1
      and DATEPART(dd,evnt_dat)  >= 1 and DATEPART(dd,evnt_dat)<=2

    GROUP BY  
        panel_descrp   
    ,   cardno 
    ,   lname

1 个答案:

答案 0 :(得分:0)

如果你想要它们,你必须将它们包含在GROUP BY子句中:

SELECT DISTINCT 
        ROW_NUMBER() OVER (ORDER BY 
                                panel_descrp   
                            ,   cardno
                            ,   lname
                           ) rid 
    ,   panel_descrp   
    ,   cardno   
    ,   lname
    ,   evnt_dat
    ,   evnt_desrp

FROM ev_log

where evnt_descrp = 'local grant' 
      and datepart(yyyy,EVNT_DAT) = datepart(yyyy,GETDATE()) 
      and DATEPART(mm,evnt_dat)   = DATEPART(mm,getdate()) -1
      and DATEPART(dd,evnt_dat)  >= 1 and DATEPART(dd,evnt_dat)<=2

    GROUP BY  
        panel_descrp   
    ,   cardno 
    ,   lname
    ,   evnt_dat
    ,   evnt_desrp
;

或者,对它们使用一些聚合函数,例如MAX(那么你不必将它们放在GROUP BY子句中,但是查询的含义可能不是你期望的那样):

SELECT DISTINCT 
        ROW_NUMBER() OVER (ORDER BY 
                                panel_descrp   
                            ,   cardno
                            ,   lname
                           ) rid 
    ,   panel_descrp   
    ,   cardno   
    ,   lname
    ,   MAX(evnt_dat)
    ,   MAX(evnt_desrp)
FROM ev_log

where evnt_descrp = 'local grant' 
      and datepart(yyyy,EVNT_DAT) = datepart(yyyy,GETDATE()) 
      and DATEPART(mm,evnt_dat)   = DATEPART(mm,getdate()) -1
      and DATEPART(dd,evnt_dat)  >= 1 and DATEPART(dd,evnt_dat)<=2

    GROUP BY  
        panel_descrp   
    ,   cardno 
    ,   lname
;