0

我有这样的查询:

SELECT v.Vtype,
       SUM(DATEDIFF(MI, t.Paydate, t.DelDate)) AS TotalDiff,
       CONVERT(DECIMAL(10, 1), 
               AVG(CONVERT(NUMERIC(18, 2), DATEDIFF(MI, t.Paydate, t.DelDate)))) AS Average
FROM   Transaction_tbl t
       LEFT JOIN VType_tbl v
         ON t.vtid = v.vtid
WHERE  t.Locid = 5
GROUP  BY v.Vtype 

平均来自 Transaction_tbl t left join VType_tbl v on t.vtid=v.vtid where t.Locid =5 group by v.Vtype

我的输出:

Vtype TotalDiff 平均
-------------------------------------------------- -
Emaar 员工 NULL NULL
正常 14044 189.8
贵宾 85 2.1
贵宾 5 2.5

但我想像这样出去:

VtypeE Etotaldiff 平均 VtypeN Ntot Naverge vtypev vtot vaverg
Emaar 法杖 null null 普通 14044 189.8 VIP 85 2.1
4

1 回答 1

1

您正试图将结果全部重新放在一行中。但是,这些列有不同的类型。这意味着内置pivot不太实用。您可以通过显式聚合原始查询来做您想做的事情:

with cte as (
      SELECT v.Vtype, SUM(DATEDIFF(MI, t.Paydate, t.DelDate)) AS TotalDiff,
            CONVERT(DECIMAL(10, 1), 
            AVG(CONVERT(NUMERIC(18, 2), DATEDIFF(MI, t.Paydate, t.DelDate)))) AS Average
      FROM   Transaction_tbl t LEFT JOIN
             VType_tbl v
             ON t.vtid = v.vtid
     WHERE  t.Locid = 5
     GROUP  BY v.Vtype 
   )
select 'Emaar Staff' as VtypeE,
       max(case when type = 'Emaar Staff' then TotalDiff end) as ETotalDiff,
       max(case when type = 'Emaar Staff' then Average end) as EAverage,
       'Normal' as VtypeN,
       max(case when type = 'Normal' then TotalDiff end) as NTotalDiff,
       max(case when type = 'Normal' then Average end) as NAverage,
       'VIP' as VtypeV,
       max(case when type = 'VIP' then TotalDiff end) as VTotalDiff,
       max(case when type = 'VIP' then Average end) as VAverage
from cte;
于 2013-07-21T12:46:47.020 回答