当前位置:编程学习 > C#/ASP.NET >>

遇到一个数据库的经典查询,求大虾帮忙,第一次发帖!

表中原始数据:
如图所示:


我想要得到结果是这样的:



写一条sql语句得到第二张图所示的结果。
--------------------编程问答-------------------- 除 --------------------编程问答-------------------- 楼上滴,就知道看戏呢? --------------------编程问答-------------------- 你的目的是把2012年的广岛软件插到上海电信中间?好怪异的想法 --------------------编程问答--------------------
引用 3 楼 weiyz2011 的回复:
你的目的是把2012年的广岛软件插到上海电信中间?好怪异的想法


不是的呀。
那个是两个不同的公司,对它进行分组查询。
主要注意看Price,如:2010年2月份的Price=2010.1+2010.2 这样的,以此类推、 --------------------编程问答-------------------- select company,sum(price) price,month1 ,year1 from table
group by year1,month1,company
order by year1 asc ,month1 asc --------------------编程问答-------------------- --------------------编程问答-------------------- select * from test1 order by year1,company,month1 --------------------编程问答-------------------- --------------------编程问答-------------------- 行转列就行了 --------------------编程问答-------------------- 真奇怪的需求 --------------------编程问答-------------------- 同意7楼,就是个简单的排序问题 --------------------编程问答-------------------- 不过需要把*改成具体的列,因为结果中没有id列
select company,price,month1,year1 from table
order by year1,company,month1  --------------------编程问答-------------------- with tb(id,company,price,month1,year1)
as(
select 1,'广岛软件',1000,1,2010 union all
select 2,'广岛软件',1500,2,2010 union all
select 3,'广岛软件',500,3,2010 union all
select 4,'上海电信',2000,1,2010 union all
select 5,'广岛软件',1000,1,2012 union all
select 6,'广岛软件',1000,2,2012 union all
select 7,'广岛软件',1000,3,2012 union all
select 8,'广岛软件',1000,4,2012 union all
select 9,'上海电信',3000,2,2012
),
source as(
select company,price,month1,year1,rowindex=row_number()over(partition by year1,company order by id) from tb
)
select company,(select sum(price) from source s2 where s2.company=s1.company and s2.year1=s1.year1 and s2.rowindex<=s1.rowindex) price,month1,year1 from source s1 --------------------编程问答-------------------- 好吧,我承认我看错了,其实就是这样:
SELECT distinct t1.[company]
      ,(select sum(t2.[price]) from [dbo].[Test1] t2 where t1.[company] = t2.[company] and t1.[year1] = t2.[year1] and t2.[month1] <= t1.[month1]) as price
      ,t1.[month1]
      ,t1.[year1]
  FROM [dbo].[Test1] t1
  order by t1.[year1], t1.[company], t1.[month1] --------------------编程问答-------------------- 看清楚需求偶,按company 的year1 的month1字段累加哦 --------------------编程问答-------------------- select a.company,(a.price+b.price) as price,a.month1,a.year1
from table a,table b
where a.company=b.company and a.year1=b.year1 and a.month1>b.month1 --------------------编程问答-------------------- --------------------编程问答-------------------- --------------------编程问答--------------------
引用 楼主 kokeaikele 的回复:
表中原始数据:
如图所示:


我想要得到结果是这样的:



写一条sql语句得到第二张图所示的结果。

order by year1 asc ,company asc
--------------------编程问答-------------------- 提问要提到点上 随便给个数据 给我结果  会给人困惑 --------------------编程问答-------------------- 我是看看  我不说话
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,