按子查询的结果分组

时间:2012-07-17 23:27:40

标签: sql tsql sql-server-2005

我试图在Group By语句中使用子查询的结果,并且发现不允许这样做。我认为有可能用CTE做到这一点,但我不确定。我正在为SQL Server 2005创建这个SQL代码。我显然不是专家。这是我写的SQL语句......

select
  sum(paxon), 
  (select id from runs as RS where RS.code = RL.runsegment) as port_id,
  date
from
  runlogs as RL
where 
  date BETWEEN '07/09/2012' and '07/16/2012'     
  and account in ('311,312,313')
  and runsegment in (select code from runsegments where org_id = 13)
group by
  date,
  port_id

当我尝试运行时,我被告知port_id是一个无效的列名。我很确定这可以通过创建临时表或CTE或可能使用JOIN来实现,但我不知道该怎么做。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

这样的事情怎么样?除非我遗漏了某些东西,否则我认为不需要子查询。

SELECT SUM(rl.paxon)
    ,r.id AS port_id
    ,rl.[date]
FROM runlogs rl
    INNER JOIN runs r
        ON r.code = rl.runsegment
    INNER JOIN runsegments rs
        ON rs.code = rl.runsegment
WHERE rl.[date] BETWEEN '20120709' AND '20120716'  
    AND rl.account in ('311','312','313')
    AND rs.org_id = 13
GROUP BY rl.[date], r.id

我不确定account in ('311,312,313')试图做什么。在我的回答中,我假设accountnvarcharvarchar,并且这三个项目中的每一个实际上都是不同的account值。如果accountint,则该行应为:AND rl.account in (311,312,313)

我还更改了您的日期以使用首选unseparated numeric strings

答案 1 :(得分:0)

一个选项是以下

select sum(sum_paxon), date, port_id from
(
select paxon,

(select id from runs as RS where RS.code = RL.runsegment) as port_id,

date from runlogs as RL

where

date BETWEEN '07/09/2012' and '07/16/2012'

and account in ('311,312,313')

and runsegment in (select code from runsegments where org_id = 13)
 ) Z
group by date, port_id