我有以下代码,当我按原样运行它时,它将返回给我我想要的数据:
select tagid,
(select TOP 1 Locations.CostCenter
from item
inner join transactions on transactions.itemid = item.id
inner join recvlocationmapping on recvlocationid = transactions.locationid
left outer join locations on locations.id = servicelocationid
where tagid = c.TagID
and costcenter != ''
and Costcenter is not null
order by transdate desc) as CostCenter
from item as c where createddate between '07-01-2012' and '07-05-2012'
当我想将 group by 添加到其中一列时,问题就来了。然后它会抛出一个错误,说该列不存在,但是当我在没有 Group By 列和名称的情况下运行查询时。
这是我遇到问题的按代码分组:
select Count(tagid),
(select TOP 1 Locations.CostCenter
from item
inner join transactions on transactions.itemid = item.id
inner join recvlocationmapping on recvlocationid = transactions.locationid
left outer join locations on locations.id = servicelocationid
where tagid = c.TagID
and costcenter != ''
and Costcenter is not null
order by transdate desc) as CostCenter
from item as c where createddate between '07-01-2012' and '07-05-2012'
group by CostCenter
我认为这是我如何返回数据的问题,但我对 SQL 的了解还不够,无法弄清楚如何解决它。