我有这样的查询:
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在t.vtid = v.vtid上加入VType_tbl v,其中t.Locid = 5 by v.Vtype
我的输出:
Vtype TotalDiff Average -------------------------------------------------- - Emaar Staff NULL NULL Normal 14044 189.8 VIP 85 2.1 VVIP 5 2.5
但我想这样出来:
VtypeE Etotaldiff Eaverage VtypeN Ntot Naverge vtypev vtot vaverg Emaar Staff null null Normal 14044 189.8 VIP 85 2.1
答案 0 :(得分: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;