SQL create variable over columns

SQL create variable over columns



I have a query that is becoming repetitive with the summation of the same columns. What I would like to do is create a variable so that my code does not become unnecessarily cluttered.
A trivial example:


SELECT
(a.col1 + a.col2 + a.col3 + a.col4 + a.col5)/2 AS half,
(a.col1 + a.col2 + a.col3 + a.col4 + a.col5)/3 AS third,
(a.col1 + a.col2 + a.col3 + a.col4 + a.col5)/4 AS fourth,
(a.col1 + a.col2 + a.col3 + a.col4 + a.col5)*2 AS twice,
b.sepCol
FROM [Table A] a
JOIN [Table B] b ON b.someCol = a.someCol



I would like to be able to remove the need to type the sum(col1...col5) into something like:


@myVar = (a.col1 + a.col2 + a.col3 + a.col4 + a.col5)
SELECT
@myVar/2 AS half,
@myVar/3 AS third,
@myVar/4 AS fourth,
@myVar*2 AS twice,
b.sepCol
FROM [Table A] a
JOIN [Table B] b ON b.someCol = a.someCol



Preferably I would like to keep this in the same query and not have to utilize a CTE or TempTable if possible.




2 Answers
2



You can use that as inner query like


SELECT
myVar/2 AS half,
myVar/3 AS third,
myVar/4 AS fourth,
myVar*2 AS twice
FROM (
SELECT (col1 + col2 + col3 + col4 + col5) as myvar, b.sepCol
FROM TableA ) xxx





I think you miss b.sepCol column here
– Sami
Aug 21 at 13:44





@Sami Yes missed that and included now. Thanks for pointing
– Rahul
Aug 21 at 14:02



I would use APPLY :


APPLY


SELECT aa.cols/2 AS half,
aa.cols/3 AS third,
aa.cols/4 AS fourth,
aa.cols*2 AS twice,
b.sepCol
FROM [Table A] a INNER JOIN
[Table B] b
ON b.someCol = a.someCol CROSS APPLY
( VALUES (a.col1 + a.col2 + a.col3 + a.col4 + a.col5)
) aa (cols);





You miss the b.sepCol column too :)
– Sami
Aug 21 at 13:46






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ

Node.js puppeteer - Use values from array in a loop to cycle through pages