1

我试图在我的 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 来实现,但我不知道该怎么做。任何帮助将不胜感激。

4

2 回答 2

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')正在尝试做什么。在我的回答中,我假设这三个项目中的每一个实际上都是不同accountnvarchar值。如果是,那么该行应该是: 。varcharaccountaccountintAND rl.account in (311,312,313)

我还更改了您的日期以使用首选的未分隔数字字符串

于 2012-07-17T23:41:31.977 回答
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
于 2012-07-17T23:32:10.690 回答