在结果查询中将多个列连接成单个列

时间:2014-06-02 18:45:59

标签: sql db2 db2-400

我需要帮助在结果查询后在单个(DB2)中添加多个列

我的查询结果如下,

EMPI   HRS  MTS  SDS
-------------------
sam    12   10   10
tukai  10   05   02

现在,我想要这个输出:

empid   Totaltimetaken
----------------------
sam     12:10:10
tukai   10:05:02

首先查询:

SELECT
    empid
    ,TOTALSECONDS/3600 AS HRS
    ,(MOD(TOTALSECONDS, 3600) /60) AS MTS
    ,(MOD(TOTALSECONDS, 60)) AS SDS
FROM 
    (SELECT
        SUM(duration) AS TOTALSECONDS
        ,empid
     FROM table
     GROUP BY empid)

从上面的查询结果中,我现在想要添加列:empid, hrs, mts, sds

我使用了这个查询但没有得到结果。任何帮助...

SELECT 
    TMP1.emp
    ,('0'||(TOTALSECONDS.TMP1)/3600)||':'||
    ('0'||(MOD(TOTALSECONDS.TMP1),3600)/60) ':'||
    MOD(TOTALSECONDS.TMP1),60) AS TOTALTIMETAKEN
    ,TMP1.TOTALSECONDS
FROM
   (SELECT 
       EMPID emp,
       SUM(DURATION) AS TOTALSECONDS
    FROM table
    GROUP BY EMPID) TMP1

这适用于IBM DB2。

2 个答案:

答案 0 :(得分:1)

您应该使用TMP1作为前缀 -

SELECT TMP1.emp, TMP1.TOTALSECONDS,
           ('0' || (TMP1.TOTALSECONDS) / 3600) || ':' ||
           ('0' || (MOD(TMP1.TOTALSECONDS, 3600) / 60) ':' ||
           MOD(TMP1.TOTALSECONDS, 60) AS TOTALTIMETAKEN
FROM (SELECT EMPID emp, SUM(DURATION) AS TOTALSECONDS
      FROM table
      GROUP BY EMPID) TMP1

答案 1 :(得分:-1)

这应该让你走上正轨......

Select One, Two
from Table

将导致2​​列看起来像

|One|   |Two|
  1       2

-

 Select Cast(One as varchar(30)) + '_' + Cast(Two as varchar(30)) as 'Concatenated'
 from Table   

结果看起来像

|Concatenated|
     1_2

*请注意,这是针对SQL Server的