Let's say I have the following range in Excel named MyRange:
This isn't a table by any means, it's more a collection of Variant values entered into cells. Excel makes it easy to sum these values doing =SUM(B3:D6) which gives 25. Let's not go into the details of type checking or anything like that and just figure that sum will easily skip values that don't make sense.
If we were translating this concept into SQL, what would be the most natural way to do this? The few approaches that came to mind are (ignore type errors for now):
MyRangereturns an array of values:-- myRangeAsList = [1,1,1,2, ...] SELECT SUM(elem) FROM UNNEST(myRangeAsList) AS r (elem);MyRangereturns a table-valued function of a single column (basically the opposite of a list):-- myRangeAsCol = (SELECT 1 UNION ALL SELECT 1 UNION ALL ... SELECT SUM(elem) FROM myRangeAsCol as r (elem);Or, perhaps more 'correctly', return a 3-columned table such as:
-- myRangeAsTable = (SELECT 1,1,1 UNION ALL SELECT 2,'other',2 UNION ALL ... SELECT SUM(a+b+c) FROM SELECT a FROM myRangeAsTable (a,b,c)Unfortunately, I think this makes things the most difficult to work with, as we now have to combine an unknown number of columns.
Perhaps returning a single column is the easiest of the above to work with, but even that takes a very simple concept -- SUM(myRange) and converts into something that is anything but that: SELECT SUM(elem) FROM myRangeAsCol as r (elem).
Perhaps this could also just be rewritten to a function for convenience, for example:






