Sql 无法获取行ID上具有左联接的和(列)
我有一个临时表,如下所示Sql 无法获取行ID上具有左联接的和(列),sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一个临时表,如下所示 ID : type : stat ---------------- 1 : t1 : 0 2 : t2 : 0 3 : t3 : 1 我想创建另一个临时表 ID : type : stat : qty ---------------------- 1 : t1 : 0 : 10 2 : t2 : 0 : 20 3 : t3 : 1 : 30 但是,数量来自另一个具有多行的表。前 ID : junk : ju
ID : type : stat
----------------
1 : t1 : 0
2 : t2 : 0
3 : t3 : 1
我想创建另一个临时表
ID : type : stat : qty
----------------------
1 : t1 : 0 : 10
2 : t2 : 0 : 20
3 : t3 : 1 : 30
但是,数量来自另一个具有多行的表。前
ID : junk : junk : qty
----------------------
1 : t1 : 0 : 5
1 : t2 : 0 : 5
2 : t3 : 1 : 15
3 : t1 : 0 : 5
3 : t2 : 0 : 20
3 : t3 : 1 : 10
这是我当前获取第一个表的查询
选择table1.ID、table1.type、table1.stat
进入诱惑1
来自表1
其中start_date>=dateADDwk,DATEDIFFwk,0,getdate,-1-sunday
开始日期我不明白你为什么使用临时表。JOIN and GROUP BY应执行您想要的操作:
select t1.ID, t1.type, t1.stat, sum(t2.qty) as qty
from table1 t1 left join
table2 t2
on t1.id = t2.id
where t1.start_date >= dateadd(week, datediff(week, 0, getdate()), -1) and --sunday
t1.start_date <= dateadd(week, datediff(week, 0, getdate()), 5) --saturday
group by t1.ID, t1.type, t1.stat;
谢谢你的回答和回答你的问题。我不知道我能做到。我并不是真的写SQL。
" Column '#temptable.type' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. "
select t1.ID, t1.type, t1.stat, sum(t2.qty) as qty
from table1 t1 left join
table2 t2
on t1.id = t2.id
where t1.start_date >= dateadd(week, datediff(week, 0, getdate()), -1) and --sunday
t1.start_date <= dateadd(week, datediff(week, 0, getdate()), 5) --saturday
group by t1.ID, t1.type, t1.stat;