我需要选择一个表列值和一些常量变量。例如,
SQL表:
Key KeyName
-------------
1 Normal
2 Basic
3 Super
常数值为R1,R2,R3,R4。
输出结果为单列:
Normal R1
Normal R2
Normal R3
Normal R4
Basic R1
Basic R2
.
.
.
Super R4
欣赏任何建议。谢谢。
答案 0 :(得分:2)
试试这个:
SELECT
T.KeyName,
TT.ConstValues
FROM Tbl T
CROSS JOIN
(VALUES ('R1'), ('R2'), ('R3'), ('R4')) TT(ConstValues)
<强> SQL FIDDLE DEMO 强>
答案 1 :(得分:1)
您需要将常量值表示为结果集,然后您可以通过从两者中选择来获取笛卡尔积。例如:
WITH ConstantValues AS
(
SELECT 'R1' AS ConstantValue
UNION ALL
SELECT 'R2'
UNION ALL
SELECT 'R3'
UNION ALL
SELECT 'R4'
)
SELECT t.KeyName, c.ConstantValue
FROM SqlTable t, ConstantValues c;
如果您希望将每对结果表示为单个结果,则可以改为使用SELECT t.KeyName + ' ' + c.ConstantValue AS ResultColumn
。
答案 2 :(得分:0)
SELECT KeyName, Value = CASE WHEN [number] = 1 THEN 'R1'
WHEN [number] = 2 THEN 'R2'
WHEN [number] = 3 THEN 'R3'
WHEN [number] = 4 THEN 'R4'
ELSE ''
END
FROM (SELECT KeyName, ROW_NUMBER OVER (PARTITION BY KeyName
ORDER BY KeyName) AS [number]
FROM MyTable) A