这个语句怎么写

fhp0234 2005-10-30 10:37:18
各位帮忙看看这个语句怎么写?我有两个表,结构如下:table1(id,node,field,grp),
table2(time,group,n1,n2,n3), 比如说table1的几组数据有:1,aa,n2,1
2,bb,n1,2
3,cc,n3,1

table2的数据有: 2005-10-26 9:04:53,2,3,5,7
2005-10-27 9:04:53,1,9,8,4
2005-10-28 9:04:53,1,8,6,2
我现在要统计出某时刻node的sum(n1),sum(n2),sum(n3),请问这个sql语句该怎么写?在线等!
...全文
178 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
fhp0234 2005-10-30
  • 打赏
  • 举报
回复
sxycgxj的意思差不多,关联的字段是是grp和group,但我是要统计某一时间段的,如班报表,日报表,月报表的该怎么写?
fhp0234 2005-10-30
  • 打赏
  • 举报
回复
字段没什么含义的,意思主要是通过table1中的字段field的值去对应table1中的字段n1,n2,n3,即table1是竖着的,而table2是横着的表结构,就是table2查询出来的结果去对应table1的字段
,不知大家对我所表达的意思明白没?
云中客 2005-10-30
  • 打赏
  • 举报
回复
首先两个表关联的字段是不是grp和group,如果是可以使用
select a.node,n1=sum(b.n1),n2=sum(b.n2),n3=sum(b.n3) from table1 a,table2 b
where a.grp=b.group
group by a.node
点点星灯 2005-10-30
  • 打赏
  • 举报
回复

declare @tab1 table(id int,node varchar(10),field varchar(10),grp int)
insert @tab1 values(1,'aa','n2',1)
insert @tab1 values(2,'bb','n1',2)
insert @tab1 values(3,'cc','n3',1)


declare @tab2 table(time1 datetime,group1 int,n1 int,n2 int,n3 int)

insert @tab2 values ('2005-10-26 9:04:53',2,3,5,7)
insert @tab2 values ('2005-10-27 9:04:53',1,9,8,4)
insert @tab2 values ('2005-10-28 9:04:53',1,8,6,2)

select * from @tab1
select * from @tab2

select a.node,n1=sum(b.n1),n2=sum(b.n2),n3=sum(b.n3) from @tab1 a,@tab2 b
where a.grp=b.group1 --and time1=@time1
group by a.node
fhp0234 2005-10-30
  • 打赏
  • 举报
回复
这么写还是不对,因为按这样分组后是table2字段中的n1,n2,n3这3个字段乘以time1字段的积,
就是没有值的字段不要列出
samfeng_2003 2005-10-30
  • 打赏
  • 举报
回复
declare @t1 table(id int,node varchar(10),field varchar(10),grp int)
insert @t1 values(1,'aa','n2',1)
insert @t1 values(2,'bb','n1',2)
insert @t1 values(3,'cc','n3',1)


declare @t2 table(time1 datetime,group1 int,n1 int,n2 int,n3 int)

insert @t2 values ('2005-10-26 9:04:53',2,3,5,7)
insert @t2 values ('2005-10-27 9:04:53',1,9,8,4)
insert @t2 values ('2005-10-28 9:04:53',1,8,6,2)

/*-----------日-------------*/
select a.node,convert(char(10),time1,120) as t,sum(b.n1) as n1,sum(b.n2) as n2,sum(b.n3) as n3
from @t1 a inner join @t2 b on a.grp=b.group1
group by a.node,convert(char(10),time1,120)
order by convert(char(10),time1,120)


/*-----------月-------------*/
select a.node,convert(char(7),time1,120) as t,sum(b.n1) as n1,sum(b.n2) as n2,sum(b.n3) as n3
from @t1 a inner join @t2 b on a.grp=b.group1
group by a.node,convert(char(7),time1,120)
order by convert(char(7),time1,120)


node t n1 n2 n3
---------- ---------- ----------- ----------- -----------
bb 2005-10-26 3 5 7
aa 2005-10-27 9 8 4
cc 2005-10-27 9 8 4
aa 2005-10-28 8 6 2
cc 2005-10-28 8 6 2

(所影响的行数为 5 行)



node t n1 n2 n3
---------- ------- ----------- ----------- -----------
aa 2005-10 17 14 6
bb 2005-10 3 5 7
cc 2005-10 17 14 6

(所影响的行数为 3 行)
fhp0234 2005-10-30
  • 打赏
  • 举报
回复
并且在查询的结果集中每隔10条记录取一次数据,这个该怎么写?

22,298

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧