Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 无法获取行ID上具有左联接的和(列)_Sql_Sql Server_Tsql - Fatal编程技术网

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;