所以,我有一个返回下表的查询:
charvar | numeric | numeric | numeric | text
cargo | qtd | valor_ust_servico | total_ust | valor_servco
name1 | 30 | 0.50 | 236.50 | US$ 20,132.02
name2 | 96 | 0.50 | 236.50 | US$ 43,169.32
name3 | 120 | 0.50 | 236.50 | US$ 12,791.11
name4 | 7708 | 0.50 | 236.50 | US$ 142,041.64
name5 | 469 | 0.50 | 236.50 | US$ 5,984.18
我需要在决赛桌上添加name1和name3。
我的代码如下
with consulta as
(
SELECT
cc.nomecategoriaservico,
max(s.nomeservico) as nomeservico,
min(vsc.valorServico) as valor_UST_Serviço,
sum(vsc.valorservico) as total_UST,
sum(vsc.valorServico*c.cotacaomoeda) as Valor_Serviço,
count(s.nomeservico) as qtd,
EXTRACT(MONTH FROM SS.DATAHORAFIM) AS MESSERVICO
FROM solicitacaoservico ss
INNER JOIN SERVICOCONTRATO SC ON SC.IDSERVICOCONTRATO = SS.IDSERVICOCONTRATO
INNER JOIN VALORSERVICOCONTRATO VSC ON VSC.IDSERVICOCONTRATO = SC.IDSERVICOCONTRATO
INNER JOIN CONTRATOS C ON C.IDCONTRATO = SC.IDCONTRATO
INNER JOIN SERVICO S ON S.IDSERVICO = SC.IDSERVICO
left JOIN CATEGORIASERVICO CC ON S.IDCATEGORIASERVICO = CC.IDCATEGORIASERVICO
WHERE ss.datahorafim BETWEEN '2017-03-01 00:00:00' AND '2017-03-31 23:59:59.999'
AND UPPER(SS.SITUACAO) = UPPER('FECHADA')
GROUP BY CC.NOMECATEGORIASERVICO, EXTRACT(MONTH FROM SS.DATAHORAFIM)
), consolidado as
(
select
0 as linha,
nomecategoriaservico AS CARGO,
qtd,
valor_UST_Serviço,
total_UST AS total_UST,
'R$' || to_char(Valor_Serviço,'9G999G999D99') as Valor_Serviço
FROM consulta
UNION ALL
SELECT
1 as linha,
'Total UST' as CARGO,
sum(qtd) as qtde,
round(sum(qtd*valor_UST_Serviço)/sum(qtd),2) valor_UST_Serviço,
sum(total_UST) as total,
'R$' || to_char(sum(Valor_Serviço),'9G999G999D99') as Valor_Serviço
FROM consulta
), fim AS (
select
CARGO,
qtd,
valor_UST_Serviço,
total_UST,
REPLACE(REPLACE(REPLACE(Valor_Serviço,' ',' '),' ',' '),' ',' ') AS Valor_Serviço
from consolidado
order by linha,CARGO
到目前为止,我所尝试过的所有内容都很接近,但不是很正确。由于格式不同,我也会得到很多错误。
EDIT1。但格式化
答案 0 :(得分:1)
CTE别名咨询:
SELECT
case when cc.nomecategoriaservico = 'name1' or name_col = 'name3' then 'name1or3' else cc.nomecategoriaservico end nomecategoriaservico,
max(s.nomeservico) as nomeservico,
min(vsc.valorServico) as valor_UST_Serviço,
sum(vsc.valorservico) as total_UST,
sum(vsc.valorServico*c.cotacaomoeda) as Valor_Serviço,
count(s.nomeservico) as qtd,
EXTRACT(MONTH FROM SS.DATAHORAFIM) AS MESSERVICO
FROM solicitacaoservico ss
INNER JOIN SERVICOCONTRATO SC ON SC.IDSERVICOCONTRATO = SS.IDSERVICOCONTRATO
INNER JOIN VALORSERVICOCONTRATO VSC ON VSC.IDSERVICOCONTRATO = SC.IDSERVICOCONTRATO
INNER JOIN CONTRATOS C ON C.IDCONTRATO = SC.IDCONTRATO
INNER JOIN SERVICO S ON S.IDSERVICO = SC.IDSERVICO
left JOIN CATEGORIASERVICO CC ON S.IDCATEGORIASERVICO = CC.IDCATEGORIASERVICO
WHERE ss.datahorafim BETWEEN '2017-03-01 00:00:00' AND '2017-03-31 23:59:59.999'
AND UPPER(SS.SITUACAO) = UPPER('FECHADA')
GROUP BY case when cc.nomecategoriaservico = 'name1' or name_col = 'name3' then 'name1or3' else cc.nomecategoriaservico end, EXTRACT(MONTH FROM SS.DATAHORAFIM)