0

我有一个这样的存储过程

ALTER procedure [dbo].[performance] 
    @startdate nvarchar(100), 
    @enddate nvarchar(100) 
as begin
   declare @date1 nvarchar(100) = convert(varchar, @startdate+' 00:00:00.000', 120)
   declare @date2 nvarchar(100) = convert(varchar, @enddate+' 23:59:59.000', 120) 

   set NOCOUNT on;

   select 
       l.LocName, v.Vtype,
       SUM(convert(numeric(18, 2), 
       DATEDIFF(MI, t.DelDate, t.Paydate))) as TotalDiff,
       [dbo].[testfunctionstacknew](CONVERT(decimal(10,1), AVG( CONVERT(NUMERIC(18,2), DATEDIFF(SS,t.Paydate,t.DelDate) ) )))  as Average
   from 
       Transaction_tbl t 
   left join 
       VType_tbl v on t.vtid = v.vtid 
   left join 
       Location_tbl l on t.Locid = l.Locid 
   where 
       t.Locid in (select t1.Locid from Transaction_tbl t1) 
       and dtime between @date1 and @date2 
       and Status = 5 
   group by 
       v.Vtype, l.LocName, l.Locid 
   order by 
       l.Locid
end

我是这样出去的:

locName   Vtype    TotalDiff   Average
Address   Normal     15         00:10:01
Adress    vip         18        00:08:01
Address   VVIP         9         00:04:00
Address    Pass        20        00:15:00
Goldsouk    normal      45       00:18:08
Goldsouk      vip        17       00:11:36
Fashion       vip        78       00:35:25
Fashion        VVip       2      00:01:00

但我需要不同模型的输出:我期望输出是这样的:

LocName     Normal      Vip      VVip        Pass        Staff
Address     00:10:01    00:08:01  00:04:00    0           0
GoldSouck    00:18:08   00:11:36   0          0           0
Fashion      0          00:35:25   00:01:00   0           0 

为了让我知道我必须使用pivot ..但我不知道如何使用它?如果有人知道,请帮我找出答案..我无法硬线我的 vtype..actulay vtype 是动态的。它来自 Vtype Table

4

1 回答 1

0

You don't need a pivot, you need 4 CASE statements.

SELECT  LocName
        ,MAX(CASE WHEN Vtype = 'Normal' THEN Average ELSE 0 END) as Normal
        ,MAX(CASE WHEN Vtype = 'Vip' THEN Average ELSE 0 END) as Vip
        ,etc
...
GROUP BY
        LocName
于 2013-09-11T12:32:32.667 回答