格式化输出的SQL查询

时间:2013-07-11 06:11:43

标签: sql sql-server

我想创建一个SQL查询,并格式化该查询的输出。

我的表格如下:

Time    Amount  Id  iMId
---------------------------------
  1      2500   1   4
  3      5000   1   4
  5     10000   1   4
  7     20000   1   4
  1      2500   2   8
  3      5000   2   8
  5     10000   2   8
  7     20000   2   8

我希望输出格式如下: -

Id  iMId Time1 Time2 Time3  Time4
----------------------------------
1   4   1     3       5       7
       2500 5000   10000     20000
2   8   1     3      5         7
       2500 5000    10000    20000

我试过了:

SELECT sProfileId,iMerchantId,'Day1','Day2','Day3','Day4',dAmount 
FROM (SELECT RM.sProfileId,RM.iMerchantId,RC.iDays,RC.dAmount 
      FROM  tblRuleByMerchant RM 
      JOIN tblAlertRuleCummulativeData RC ON (RM.sProfileId=RC.sProfileId) ) AS d
PIVOT (max(RM.sProfileId) FOR RM.iMerchantId IN ('Day1','Day2','Day3','Day4')) piv

1 个答案:

答案 0 :(得分:1)

我认为Time列的值已修复且为1,3,5,7

查询下方与您想要实现的类似。

select distinct T.id,T.iMid,
  (select amount from myTable
  where time = 1 and id = T.id and iMid = T.iMid) as Time1,
  (select amount from myTable
  where time = 3 and id = T.id and iMid = T.iMid) as Time2,
  (select amount from myTable
  where time = 5 and id = T.id and iMid = T.iMid) as Time3,
  (select amount from myTable
  where time = 7 and id = T.id and iMid = T.iMid) as Time4,
  2 as level
  from myTable T
 union All
select distinct T.id,T.iMid,1,3,5,7,1
  from myTable T
 order by id,level

Here is the SQLFiddel DEMO ,与您在问题中提到的模式类似。