我有一个表varchar,int,int,如下所示:
OS MinSP MaxSP
-- ----- -----
2000 4 4
XP 2 3
Vista 0 2
7 0 1
我想要的是一个查询,它会生成一个像这样的值列表:
修改的
尽管MinSP和MaxSP在我的原始示例中永远不会超过一个,但它们可能相同或分开不止一个。我已经改变了这个例子来说明。
答案 0 :(得分:1)
快速回答:
Select OS + ' SP' + Convert(varchar(50),MinSp) as col1 from TABLE
UNION
Select OS + ' SP' + Convert(varchar(50),MaxSp) as col1 from TABLE
根据需要添加ORDER BY。
但请看我对你的问题的评论。
答案 1 :(得分:1)
SELECT CASE WHEN MinSP = '0' THEN OS ELSE OS + ' SP' + cast(MinSP as
nvarchar(10)) END AS Results, MaxSP
FROM OS
UNION
SELECT CASE WHEN MaxSP = '0' THEN OS ELSE OS + ' SP' + cast(MaxSP as
nvarchar(10)) END AS Results, MaxSP
FROM OS
ORDER BY MaxSP DESC
编辑:
根据您的新标准,我假设您将拥有一个名为SPNums的第二个表,其中填充了您认为需要的数量,从0开始。
SPNum
-----
0
1
2
3
4
5
6
然后查询:
SELECT CASE WHEN SPNum = '0' THEN OS ELSE OS + ' SP' + cast(SPNum as
nvarchar(10)) END AS Results
FROM OS
LEFT OUTER JOIN SPNums ON SPNum >= MinSP AND SPNum <= MaxSP
ORDER BY OS
答案 2 :(得分:1)
您需要Tally table来执行以下操作,但它会击败游标并随着下一个已发布的操作系统动态增长。您的计数表也必须为零。
编辑:修正了拼写错误并添加了第二个版本
版本1(您还没有Tally表): 这会使用sys.all_columns动态生成数字表。有很多方法可以做到这一点,但你明白了。
;WITH Tally(N)
AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 --minus one to make this zero based
FROM sys.all_columns C)
SELECT OS + CASE WHEN N > 0 THEN ' SP' + CAST(B.N AS char(1))
ELSE ''
END
FROM dbo.Test A
INNER JOIN Tally B ON B.N >= A.MinSp
AND B.N <= A.MaxSp
第二版(你有一个基于零的理货表):
SELECT OS + CASE WHEN N > 0 THEN ' SP' + CAST(B.N AS char(1))
ELSE ''
END
FROM dbo.Test A
INNER JOIN dbo.Tally B ON B.N >= A.MinSp
AND B.N <= A.MaxSp