排除Group BY上的列

时间:2015-01-19 07:14:47

标签: sql stored-procedures

我在下面有一个查询,我唯一的问题是在group by子句中排除某些列。

SELECT * FROM OPENQUERY
(server, 
''select 
    b.devdate as DevDate,   
    c.devWidth AS DevWitdh,
    c.devHeight as DevHeight,
    a.devQty AS DevQTY,     
    c.devCode AS DevCode,
    d.devdesk AS DevDesc,

 from 
    server.a_STAT a,
    server.a_cust b,
    server.a_post c,
    server.dev_date d,
    server.a_adress e
 where 
       a. DevQTY!=0 and a.AUF_NR=b.AUF_NR and a.auf_pos = c.auf_pos AND
       b.AUF_NR=c.AUF_NR AND 
       b.AUF_OFF = 0 AND  
       d.idnr=  c.GLAS1  AND    
       b. dev_date ''''' + @DTFrom + ''''' AND '''''+ @DTTo+'''''   '


SET @ENDTSQLSTATEMENT1 =' GROUP BY b. dev_date,c.GLAS1, d.gl_bez, c. DevWitdh, c. DevHeight , a. DevQTY ORDER BY b. dev_date '' )'

在我的选择中,我想添加客户名称和项目,但我不想在group by子句中包含它。请帮帮我......

2 个答案:

答案 0 :(得分:0)

不可能我害怕!

想一想:如果你有一张桌子:

foos   bars
-----  -----
foo1   bar1
foo2   bar2
foo2   bar3

你是否要运行“select foos,bars from foobars group by foos”,它会为“foo2”显示哪个值?

你可以通过编写MAX(bars)这样的聚合函数来解决这个问题,这会给你"foo2 bar3",这可能是你想要的,也可能不是你想要的。

答案 1 :(得分:0)

如果我的问题正确无误,那么您需要2个查询才能执行此操作。 就像后面的帖子一样:

select e.empID, fname, lname, title, dept, projectIDCount
from
(
   select empID, count(projectID) as projectIDCount
   from employees E left join projects P on E.empID = P.projLeader
   group by empID
) idList
inner join employees e on idList.empID = e.empID

T-SQL GROUP BY: Best way to include other grouped columns