当前位置: 代码迷 >> Sql Server >> sqlserver!遇到难题了
  详细解决方案

sqlserver!遇到难题了

热度:12   发布时间:2016-04-25 01:18:27.0
sqlserver高手请进!遇到难题了!
有一张表记录消费信息的table1
id uid money
1 2 3
2 2 5
3 1 5
4 8 3
5 5 10
6 3 20
7 8 6
8 6 9
9 8 3
10 1 60
11 3 8
12 3 5
13 5 6
14 2 10
15 3 10

现在想查出每一个uid 所消费的money.
uid 是从表table2是查询所得。

也就是说,从table2中查询不重复uid 去对应表table1中的uid,再查出每个uid的总消费(money)情况

求sql语句

速度解决,速度给分!



------解决方案--------------------
SQL code
select a.uid,sum(b.money) from table2 a left join table1 bgruop by a.uid
------解决方案--------------------
不怎么清晰的感觉。。。
table1的uid是有重复的 那到时候算总消费依据什么呢
额 或许我理解能力不够高啊
------解决方案--------------------
select sum([money]),uid summoney from table1 where uid in 
(select uid from table2)
group by table1.uid
------解决方案--------------------
SQL code
select sum([money]),a.uid summoney from table1  as ajoin table2 as b on a.uid =b.uid group by a.uid
------解决方案--------------------
探讨

id uid money
1 2 3
2 2 5
3 1 5
4 8 3
5 5 10
6 3 20
7 8 6
8 6 9
9 8 3
10 1 60
11 3 8
12 3 5
13 5 6
14 2 10
15 3 10

我想得到的结果是

uid money
2 sum(money)
1 sum(money)
8 ……

------解决方案--------------------
SELECT DISTINCT uid,SUM(money)OVER(PARTITION BY uid ) FROM 有一张表记录消费信息的table1
------解决方案--------------------
探讨
id uid money
1 2 3
2 2 5
3 1 5
4 8 3
5 5 10
6 3 20
7 8 6
8 6 9
9 8 3
10 1 60
11 3 8
12 3 5
13 5 6
14 2 10
15 3 10

我想得到的结果是

uid money
2 sum(money)
1 sum(money)
8 sum(money)
……

------解决方案--------------------
探讨

引用:

引用:

id uid money
1 2 3
2 2 5
3 1 5
4 8 3
5 5 10
6 3 20
7 8 6
8 6 9
9 8 3
10 1 60
11 3 8
12 3 5
13 5 6
14 2 10
15 3 10

我想得到的结果是

uid money
2 sum(……

------解决方案--------------------
SQL code
create table #T ([ID] int identity(1,1) NOT NULL,[uid]int NULL,[money] decimal(12,2) NULL)  INSERT INTO #TSELECT  2, 3 union allSELECT  2 ,5 union allSELECT   1, 5 union allSELECT   8, 3 union allSELECT   5, 10 union allSELECT  3, 20 union allSELECT   8, 6 union allSELECT   6, 9 union allSELECT   8, 3 union allSELECT   1, 60 union allSELECT   3, 8 union allSELECT   3, 5 union allSELECT   5, 6 union allSELECT  2, 10 union allSELECT  3, 10 SELECT DISTINCT uid,SUM(money)OVER(PARTITION BY uid ) Ssum FROM #t drop table #T(15 行受影响)uid         Ssum----------- ---------------------------------------1           65.002           18.003           43.005           16.006           9.008           12.00(6 行受影响)
------解决方案--------------------
貌似这个快很多
SQL code
create table #T ([ID] int identity(1,1) NOT NULL,[uid]int NULL,[money] decimal(12,2) NULL)  INSERT INTO #TSELECT  2, 3 union allSELECT  2 ,5 union allSELECT   1, 5 union allSELECT   8, 3 union allSELECT   5, 10 union allSELECT  3, 20 union allSELECT   8, 6 union allSELECT   6, 9 union allSELECT   8, 3 union allSELECT   1, 60 union allSELECT   3, 8 union allSELECT   3, 5 union allSELECT   5, 6 union allSELECT  2, 10 union allSELECT  3, 10 go select uid,sum(money)Ssum from #t group by uid drop table #T
  相关解决方案