T-SQL计算与GUID关联的字段数,并从另一个与相同GUID关联的表中获取字段总和

时间:2013-09-25 13:59:07

标签: sql sql-server tsql ssms

编辑: 大家好,

我想通了

select LI.ProjectId, count(*) as numLineItems
into #temp
from dbo.SQLLineItems as LI
group by LI.ProjectId
having COUNT(*) < =200

select numLineItems, count(*), SUM(PT.GrandTotalSell) from
#temp
inner join dbo.SQLProjectTotals as PT
on PT.ProjectId = #temp.ProjectId
group by numLineItems;

感谢您的帮助。


我有两个包含项目信息的表。表1包含LineItems,每个LineItem都具有该表唯一的GUID和ProjectID的GUID。每个ProjectID都有重复项,因为一个ProjectID可以有多个LineItem。

表2按项目ID链接到表1,GUID在该表中是唯一的。表2还包含每个项目的价格。

我想按LineItem的数量细分项目,看看有多少项目是1,2,3,4 ......项目项目。

我写了一个有效的查询:

use FieldedProjects;

select LI.ProjectId, count(*) as numLineItems
into #temp
from dbo.SQLLineItems as LI
group by LI.ProjectId
having COUNT(*) < =15

select numLineItems, count(*) from
#temp
group by numLineItems;

但现在我想修改它以显示价格总计。因此,1个项目项目的总项目价格为100,2个项目项目为300,...

我在想像

这样的东西
use FieldedProjects;

select LI.ProjectId, count(*) as numLineItems, SUM(PT.GrandTotalSell) as projectTotal
into #temp
from dbo.SQLLineItems as LI
inner join dbo.SQLProjectTotals as PT
on LI.ProjectID = PT.ProjectID
group by LI.ProjectId
having COUNT(*) < =15

select numLineItems, count(*), projectTotal from
#temp
group by numLineItems;

但是它给了我一个错误,因为projectTotal不包含在聚合函数中。它应该是

select numLineItems, count(*), SUM(projectTotal) from

1 个答案:

答案 0 :(得分:0)

select *
from dbo.SQLProjectTotals as PT
cross apply
(
    select count(*)
    from dbo.SQLLineItems LI
    where LI.ProjectID = PT.ProjectID
) items(Count)
where items.Count <= 15