这是我的表格样本
[myTable]
id | random1 | random2 | random3 | random4
1 | 123 | 5357 | 10 | 642
2 | 423 | 34 | 20 | 531
3 | 9487 | 234 | 30 | 975
4 | 34 | 123 | 40 | 864
这是我当前的查询,但它并不像我期望的那样工作:
SELECT
cols.*,
(SELECT SUM(cols.column_name) FROM myTable t)
FROM
(SELECT
table_name::text, column_name::text
FROM
information_schema.columns
where
table_name = 'myTable') as cols
我收到错误:函数sum(text)不存在 - 这是有道理的。我非常确定mysql可能会非常混乱以允许这样的引用,但我不知道如何在postgres中执行此操作。
我真正想拥有的是最终结果......
table_name | column_name | sum
myTable | id | 10
myTable | random1 | 10067
myTable | random2 | 5748
myTable | random3 | 100
myTable | random4 | 3012
我想进一步深入了解这个问题,但我真的很想知道能否引用列名。
答案 0 :(得分:0)
SQL查询是静态的。他们从先前已知的表中选择先前已知的列。你不能让他们从数据库字典中查找表名和列,然后神奇地将这些名称粘合到自己身上。
你可以做什么:编写一个程序(Java,C#,PHP,无论你喜欢什么),执行以下操作:
答案 1 :(得分:0)
declare @tableName varchar(255) = 'myTable' --Change this to the table name you want
/*create table and column name dataSet and insert values*/
if object_id('tempdb.dbo.#objectSet') is not null
drop table #objectSet
create table #objectSet
(table_name varchar(256),
columnID int,
column_name varchar(256),
[sum] int)
insert into #objectSet
(table_name,
columnID,
column_name)
select O.name table_name,
C.column_id columnID,
C.name column_name
from sys.all_objects O
join sys.all_columns C
on O.object_id = C.object_id
join sys.types T
on C.user_type_id = T.user_type_id
where O.object_id = object_id(@tableName)
and T.name in ('int', 'tinyint', 'smallint', 'bigint') --Columns with Aggregatable datatypes only, all other columns will be excluded from the set.
/*Create loop variables for each column*/
declare @SQL as varchar(4000),
@counter int = 1,
@maxCount int
select @maxCount = SQ.maxCount
from ( select count(*) maxCount
from #objectSet OS) SQ
/*Run loop, updating each column as it goes*/
while @counter <= @maxCount
begin
select @SQL = 'update OS set OS.[sum] = SQ.[sum] from #objectSet OS join (select sum(DS.' + OS.column_name + ') [sum] from ' + @tableName + ' DS) SQ on OS.column_name = ''' + OS.column_name + ''''
from #objectSet OS
where OS.columnID = @counter
exec (@SQL)
select @counter += 1
end
/*Display Results*/
select OS.table_name,
OS.column_name,
OS.[sum]
from #objectSet OS
使用系统对象表,一些动态T-SQL和循环应该这样做。