我有两个桌子。
表1
-----RID------URID-----Status-----
1 1 0
1 2 1
1 3 3
2 4 0
表2
-----RID----Success------Errors---
1 2 1
2 1 0
我想为表1中的每个名称计算表2中的所有错误(状态> 1),所有成功(状态<2)。像这样:
select distinct T1.[Name]
,count(T2.URID) as Error
,count(T3.URID) as Success
FROM [dbo].[Table 1] T1
left join [dbo].[Table 2] T2
on T2.RID = T1.RID and T2.Status > 1
left join [dbo].[Table 2] T3
on T3.RID = T1.RID and T3.Status < 2
group by RID
这是我要使用的查询,但不起作用...认为在联接中已经过滤会很明智。...我在这里做错了什么?
dropApples(){
let apple;
var random = 2;
if(this.state.apples){
this.setState(prevState => ({
apples: prevState.apples.map(apple => {
if (apple.id == random) return {...apple, status: 'falling'}
return apple
})
}))
}
}
答案 0 :(得分:2)
您也可以通过以下方式实现这一目标,
SELECT * INTO #T FROM (SELECT CASE WHEN T.[STATUS]>1 THEN COUNT(T.[STATUS]) ELSE 0 END [ERROR],
CASE WHEN T.[STATUS]<2 THEN COUNT(T.[STATUS]) ELSE 0 END [SUCCESS],
T2.NAME FROM TEST1 T2 INNER JOIN TEST2 T ON T.RID=T2.RID
GROUP BY T.[STATUS],T2.[NAME]) T
SELECT NAME,SUM([SUCCESS]) [SUCCESS],SUM(ERROR)[ERROR] FROM #T GROUP BY NAME
答案 1 :(得分:0)
您可以进行聚合:
select t1.rid, t1.name,
sum(case when status > 1 then 1 else 0 end) as error,
sum(case when status < 2 then 1 else 0 end) as success
from table1 t1 inner join
table2 t2
on t2.rid = t1.rid
group by t1.rid, t1.name
但是,如果您有DISTINCT
子句,则此处不需要GROUP BY
。
答案 2 :(得分:0)
使用条件聚合:
select T1.[Name],
sum(case when t2.status > 1 then 1 else 0 end) as errors,
sum(case when t2.status < 2 then 1 else 0 end) as success
from [dbo].[Table 1] T1 left join
[dbo].[Table 2] T2
on T2.RID = T1.RID
group by T1.RID, T1.[Name];
通过用于定义每一行T1.Name
的列进行聚合也很重要。我不确定T1.RID
中是否需要group by
,但是您的版本中是否有它。
答案 3 :(得分:0)
这将起作用:
create table ns_999(col1 number,col2 number,col3 number);
insert into ns_999 values( 1,1,0);
insert into ns_999 values(1,2 ,1);
insert into ns_999 values(1,3,3);
insert into ns_999 values(2,4,0);
SELECT * FROM ns_999;
select col1,
sum(case when col3>1 then 1 else 0 end ) as errors,
sum(case when col3<2 then 1 else 0 end) as sucess
from ns_999
group by col1;
示例输出:
RID FALIURE SUCCESS
1 1 2
2 0 1