我有以下查询:
select *, sum(hrs.WPTOTT) as "Hours"
from mstwmlt
inner join MSTWMPRD hrs
ON hrs.WPOPID = wtopid and hrs.WPTRAN = wtttyp
and (wttdte BETWEEN hrs.WPSDTE AND hrs.WPEDTE)
where (wtwh = ? OR ? = '*ALL')
AND (wtopid = ? OR ? = '*ALL')
AND (wtttyp = ? OR ? = '*ALL')
and ((wtco|| '/' || wtdiv) = ?)
order by wttdte, wtopid, wtttme, wtttyp
我需要选择所有内容和总和,有没有办法在不为每个字段编写长选择查询的情况下执行此操作?
答案 0 :(得分:1)
SUM
无法与其他列一起应用和选择,而不会在这些列上使用GROUP BY
。
答案 1 :(得分:0)
在几乎所有MySQL以外的数据库中,您都可以执行以下操作:
with t as (
select *
from mstwmlt
inner join MSTWMPRD hrs
ON hrs.WPOPID = wtopid and hrs.WPTRAN = wtttyp
and (wttdte BETWEEN hrs.WPSDTE AND hrs.WPEDTE)
where (wtwh = ? OR ? = '*ALL')
AND (wtopid = ? OR ? = '*ALL')
AND (wtttyp = ? OR ? = '*ALL')
and ((wtco|| '/' || wtdiv) = ?)
)
select t.*,
(select sum(wpptott) from t) as Hours
from t
order by wttdte, wtopid, wtttme, wtttyp
不幸的是,我怀疑你正在使用MySQL(因为它是你的查询不会产生编译时错误的唯一引擎,因为SUM
没有GROUP BY
子句的存在。在这种情况下,您基本上有三个合理的选择: