合并SQL中的行

时间:2014-12-18 15:18:13

标签: php sql pervasive

我的表格如下:

Dept          Wk1          Wk2
100           25           50
200           25           50
300           25           50
400           25           50
500           25           50

我的结果需要如下所示:

Dept          Wk1          Wk2
100           25           50
200           25           50
300           25           50
400           50           100

值得注意的事情;数据库是Pervasive PSQL10,我用PHP来处理结果。我想在PHP中进行这种合并,但理想情况下是否可以在查询中完成,这将节省我对额外代码的需求。

组合行的原因是,在拉取数据时,2个depts将被视为一个。

我想我已经过度思考了,但是我已经探索了工会,分组和东西(我可能错误地使用了),没有什么能给我我需要的东西。

我们非常感谢任何帮助或方向,因为我到目前为止所阅读的内容都是针对具有相同值但没有不同的行。

以下是我的查询实际情况:

SELECT
dept_workcenter,
SUM(case when right(date_sequence,2) between 0 and 7 then hours_worked else 0 end) as wk1,
SUM(case when right(date_sequence,2) between 8 and 14 then hours_worked else 0 end) as wk2,
SUM(case when right(date_sequence,2) between 15 and 21 then hours_worked else 0 end) as wk3,
SUM(case when right(date_sequence,2) between 22 and 28 then hours_worked else 0 end) as wk4,
SUM(case when right(date_sequence,2) between 29 and 31 then hours_worked else 0 end) as wk5
FROM job_detail
WHERE job between '017079' AND '017207'
AND date_sequence BETWEEN '141200' and '141231'
AND dept_workcenter != ''
GROUP BY dept_workcenter
HAVING SUM(hours_worked) <> '0'
AND SUM(hours_worked) > '0.05';

3 个答案:

答案 0 :(得分:0)

所以基本上取500并将其与400合并?

SELECT Dept, SUM(Wk1) AS Wk1, SUM(Wk2) AS Wk2
FROM yourtable
GROUP BY Dept IN (400,500), Dept

答案 1 :(得分:0)

您可以在case

中使用group by语句
select (case when dept in (400, 500) then 400 else dept end) as dept,
       sum(wk1) as wk1, sum(wk2) as wk2
from table t
group by (case when dept in (400, 500) then 400 else dept end)
order by dept;

答案 2 :(得分:0)

这在报告中并不常见。处理此问题的典型方法是生成一个临时表,您可以在其中将500修改为400,然后执行GROUP BYSUM。随着时间的推移,报告变得越复杂,此方法将变得更加有用。

create table #DeptReptTable from select * from department;

update #DeptReptTable set Dept = 400 where Dept = 500;

select Dept, SUM(Wk1) Wk1, SUM(Wk2) Wk2 from #DeptReptTable group by Dept

drop table #DeptReptTable

注意:临时表前面的#是Sybase-ism,它将创建一个绑定到当前SQL连接/会话的表。我不知道这种魔法是否适用于Pervasive。