如何使用动态选择的列名在选择查询中求和? [英] How to use a dynamic selection of column names to sum in a select query?
问题描述
我想我可能在处理这一切都是错误的,所以如果我知道,请告诉我!
I think I may be approaching this all wrong so if I am please let me know!
我有一张看起来像这样的桌子:
I have a table that looks something like this:
Id | Region | 0 | 10 | 20 | 30 | 40 | 50
-----------------------------------------
01 | London | 24 | 45 | 38 | 29 | 36 | 49
-----------------------------------------
02 | Bham | 27 | 42 | 33 | 31 | 38 | 41
-----------------------------------------
03 | Lpool | 23 | 38 | 29 | 31 | 34 | 49
其中一行代表一个区域,然后是 0-10、10-20、20-30 等年龄段的人口.我希望能够选择给定年龄范围的人口总和.例如.10-40:
Where a row represents a region followed by populations in the age ranges 0-10, 10-20, 20-30 etc. I would like to be able to select a sum of the population for a given age range. E.G. for 10-40:
SELECT (p.10 + p.20 + p.30) FROM Population p WHERE Id = 01
如何使用自定义范围执行此操作?例如.一个存储过程,它接受年龄范围的最小值和最大值.SP 不是问题,只是动态定义要求和的列范围的能力.
How do I go about doing this with a custom range? E.g. a stored procedure that takes in a min and max value for the age range. The SP isn't the problem, just the ability to dynamically define a range of columns to sum.
推荐答案
你可以使用'AND'操作给出另一个条件你做错了
You can give another condition using 'AND' operation and you are doing wrong
SELECT (p.10 + p.20 + p.30) FROM Population p WHERE Id = 01
您缺少人口 p 之间的下划线.别的东西试试这个:
you are missing either underscore between population p. Something else try this:
SELECT * FROM table WHERE BETWEEN 10 and 40 AND id=id_no
这篇关于如何使用动态选择的列名在选择查询中求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!