我有2个表(每个表有两个相同的结构) 我用波纹管代码得到两个表的总和。 现在我想查找上个月的记录总和和当月的总和,并比较它们。 如果前一个月的总和大于当前月份的总和,则选择。如果没有,则不选择
Table 1 Table 2<br>
StudentId=1 Score=50 Date =2017/01/01 StudentId= 1 Score=100 Date =2017/01/01<br>
StudentId=1 Score=20 Date =2017/02/01 StudentId= 1 Score=10 Date =2017/02/01<br>
StudentId=2 Score=60 Date =2017/01/01 StudentId= 2 Score=100 Date =2017/01/01<br>
StudentId=2 Score=540 Date =2017/02/01 StudentId= 2 Score=100 Date =2017/02/01<br>
当前结果:
StudentId HighScoreUser<br>
1 180<br>
2 800<br>
---------------------------------<br>
我想要的结果:
StudentId Prev Month(2017/01/01) Current Month(2017/02/01)<br>
1 150 30<br>
2 160 640<br>
1 - &gt; 150> 30 - &gt;真的吗? - &GT;是的,所以必须选择
结果(选定值)= StudentId,(Sum prev Month - Sum Current Month)
<br>`CREATE PROCEDURE SelectTopMonth
@Date1 NVARCHAR(12),
@Date2 NVARCHAR(12)
AS
SELECT StudentId, ISNULL(SUM(Score),0) As HighScoreUser
FROM (SELECT StudentId, Score FROM tbl_ActPoint WHERE Date >= @Date1 AND Date <= @Date2
UNION ALL
SELECT StudentId, Score FROM tbl_EvaPoint WHERE Date >= @Date1 AND Date <= @Date2
) as T
GROUP BY StudentId ORDER BY HighScoreUser DESC
RETURN 0`
答案 0 :(得分:0)
我认为您希望看到如下数据:
Select StudentId, [2017/01/01] as [Prev Month(2017/01/01)],
[2017/02/01] as [Current Month(2017/02/01)] from (
Select * from t1
Union all
Select * from t2
) a
pivot (sum([Score]) for [Date] in ([2017/01/01],[2017/02/01]) ) p
Where [2017/01/01] > [2017/02/01]
答案 1 :(得分:0)
您可以使用SQL Server的主要分析功能来获得结果。
<强> TABLE1 强>
create table table1
(
studentid integer,
score integer,
date date
);
insert into table1 values(1,50,'2017/01/01');
insert into table1 values(1,20,'2017/02/01');
insert into table1 values(2,60,'2017/01/01');
insert into table1 values(2,540,'2017/02/01');
<强> TABLE2 强>
create table table2
(
studentid integer,
score integer,
date date
);
insert into table2 values(1,100,'2017/01/01');
insert into table2 values(1,10,'2017/02/01');
insert into table2 values(2,100,'2017/01/01');
insert into table2 values(2,100,'2017/02/01');
查询:
with data as (
select table1.studentid , (table1.score + table2.score) as pre_score, table1.date,
lead((table1.score + table2.score),1) over(partition by table1.studentid order by table1.studentid,table1.date)
as cur_score
from table1 join table2
on table1.studentid = table2.studentid
and table1.date = table2.date
)
select * from data
where cur_score is not null
and pre_score > cur_score
根据您的评论添加此条件&#34;和pre_score&gt; cur_score&#34 ;.