我需要创建一个选择所有表列和新列“sum”的查询, 像这样的东西:
SELECT *,
sum(amount) as `items_total`
FROM mytable
WHERE ...
任何想法??
答案 0 :(得分:2)
SELECT * , (SELECT sum(amount)
FROM mytable
WHERE ...) as `items_total`
FROM mytable
WHERE ...
答案 1 :(得分:1)
按以下方式尝试 -
SELECT col1,
sum(amount) as items_total
FROM mytable
WHERE mycol = <condition>
GROUP BY col1;
答案 2 :(得分:1)
您可以使用子选择来计算总和:
select t.*, (select sum(amount) FROM mytable) as `items_total`
from mytable t
答案 3 :(得分:0)
将a,b,c和d视为表中的列名,而colsum是该特定列的总和。
我认为这应该有用
select colname ,colsum from (select 'a' colname , sum(a) colsum from tablename union all select 'b' colname ,sum(b) colsum from tablename union all
select 'c' colname , sum(c) from tablename union all select 'd' colname , sum(d) colsum from tablename ) tablename where (condition) order by colsum asc;
如果您只需要表格中所有列的列名,请使用。
SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='database_name' AND `TABLE_NAME`='table_name'