比较两个 sql 输出

Compare two sql outputs

我有一个table,它必须类似于年度歌曲排行榜。从1999年到2014年,每年包含2000首歌曲及其位置。

我要把明年所有上榜的歌曲都展示出来

table 包含一个 SONGID(PK,FK,int,not null)LISTYEAR(PK,int,not null)和 POSITION(int,not null)

目标是编写一个带有 1 个给定参数的存储过程,一年与(自己生成的)下一年进行比较,并在图表中显示已上升的歌曲。

例如:

用户将变量@firstear 的值“2012”传递给存储过程。

服务器然后取这个变量加一放到下一个变量@secondyear,当然应该是2013。

应该有一个只有一个 table 的输出,它应该有 'Songname' 'Position in @firstyear' 和 'Position in @secondyear' 作为 headers。

值 'position in @secondyear' 应该总是高于 'position in @firstyear' 因为它只需要显示上升的歌曲。

我怎样才能做到这一点? mssql中有没有比较1table?

里面的值的方法

编辑:

愚蠢的我没有给你提供示例数据:

http://puu.sh/iihTc/4518dbcea9.png <- 数据库图

http://puu.sh/iii2r/a04d639f2c.png <- 这三个 tables

中的一些示例数据

输出示例将在评论中

请注意,只有排名上升的歌曲才能输出

我想你想要这个

declare @year as int = 2011
select a.songid, a.position, b.position from YourTable a
inner join YourTable b on a.songid = b.songid
where a.YEAR = @year and b.year = @year + 1 and a.position > b.position

见下文,只有歌曲 2 从 2011 年到 2012 年向上移动,因此显示在结果中

就个人而言,我不会为此使用变量。我会加入 table 回到自身。如果您正在处理非常大的数据集(数亿行),您可能希望对两种方式进行性能测试以确保,但是 JOIN 将 table 返回自身对我来说更有意义.

CREATE TABLE dbo.AnnualSongChart 
(
    SongID INT NOT NULL
    , ListYear INT NOT NULL
    , Position INT NOT NULL
    , SongName VARCHAR(50)
)

INSERT INTO dbo.AnnualSongChart(SongID, ListYear, Position, SongName)
SELECT 1, 2012, 14, 'Grieg: Peer Gynt: In The Hall of the Mountain King'
UNION ALL
SELECT 1, 2013, 15, 'Grieg: Peer Gynt: In The Hall of the Mountain King'
UNION ALL
SELECT 2, 2012, 12, 'Wagner: Die Walkure'
UNION ALL
SELECT 2, 2013, 11, 'Wagner: Die Walkure'

--Code to pull your report
SELECT DISTINCT
    CurrentYear.ListYear
    , CurrentYear.SongName
    , CurrentYear.Position 
FROM dbo.AnnualSongChart CurrentYear
JOIN dbo.AnnualSongChart LastYear
ON 
    CurrentYear.ListYear = LastYear.ListYear + 1
    AND CurrentYear.SongID = LastYear.SongID
WHERE 
    CurrentYear.Position < LastYear.Position 
    -- AND CurrentYear.ListYear = 2013

如果您只想获取特定年份的数据,请为您要提取的年份启用 WHERE 子句条件。请注意,这都是猜测,因为您的原始问题不包括 table 定义或示例数据。如果这不能为您提供所需的输出,请编辑您的原始问题。