如果匹配条件,c#在sql行中计数 [英] c# count in sql row if match condition

查看:69
本文介绍了如果匹配条件,c#在sql行中计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好兄弟!我是新的c#和sql

i现在需要你的帮助^^!



所以,我有一张这样的表



id,parent_id,name

1,0,max

2,1,john

3,1,sean



4,2,truong

5,2,muong

。 .......



(你会看到id 1有2个孩子,id 2有2个孩子)



i想要使代码可以检查sql数据,如果'id'有2'parent_id'将切换到下一个'id',如果有新的数据插入。 (ps:每个'id'只能容纳2个孩子)

解决方案

所以SQL查询的格式如下:



从[table [join table2 [etc]]中选择[column [,secondcolumn [etc]]



[where子句[和|或] secondclause [etc]]]

[按字段分组[,secondclause [etc]]]

[有子句[和|或secondclause [etc]]]



where子句在平面表上运行,having子句在聚合上运行。



所以,我们可以得到使用一组聚合:



 选择 parent_id,Count(* ) as  '  count' 
来自 table
group by parent_id





Thi列表将如下所示:

parent_id,count

0,1

1,2

2, 2



我们可以在聚合字段'count'上添加一个having子句:



 选择 parent_id,计数(*) '  count' 
来自 table
group by parent_id
count(*)< 2





现在我们的结果看起来像

parent_id,count

0,1





这就是你需要的吗?


Hi brother! im new in c# and sql
i need your help aout it now ^^!

so, i have a table like this

id, parent_id, name
1, 0, max
2, 1, john
3, 1, sean

4, 2, truong
5, 2, muong
........

(you will see id 1 have 2 child and id 2 have 2 child)

i want to make code can check in sql data if 'id' have 2 'parent_id' will switch to next 'id' if have new data insert. (ps: each 'id' just can hold 2 childs)

解决方案

So the format of an SQL query is as follows:

Select [column [, secondcolumn [etc]]
from [table [join table2 [etc]]
[where clause [and|or secondclause [etc]]]
[group by field [, secondclause [etc]]]
[having clause [ and|or secondclause [etc]]]

where clause operates on the flat table, the having clause operates on aggregates.

So, we can get the aggregate using a group by:

Select parent_id, Count(*) as 'count'
from table
group by parent_id



This list will look like this:
parent_id, count
0, 1
1, 2
2, 2

we can then add a having clause on the aggregate field 'count':

Select parent_id, Count(*) as 'count'
from table
group by parent_id
having count(*) < 2



Now our results look like
parent_id, count
0, 1


Is that what you needed?


这篇关于如果匹配条件,c#在sql行中计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆