我们如何在图像中以以下方式转动查询

时间:2017-05-20 13:06:17

标签: sql-server sql-server-2008 sql-server-2005 sql-server-2012

我尝试将表格转移到下面的图像,但我失败了,我需要的最终结果如下 enter image description here

我使用的查询是

SELECT COUNT(T.TTOutID) AS Currenct, TTOutTargetTrxnCount AS Targets, 
 B.BranchCode ,
ROW_NUMBER() OVER (Order BY COUNT(T.TTOutID) DESC) AS RANK,
CAST((CAST (COUNT(T.TTOutID) AS DECIMAL)/CAST (TTOutTargetTrxnCount AS decimal))*100 AS decimal (4,2)) AS Percentages ,
TTOutTargetTrxnCount-COUNT(T.TTOutID) as Difference
FROM ALX_SalesTargets S
LEFT JOIN ALX_TTOut T ON S.BranchID=T.BranchID
LEFT JOIN ALX_Branches B ON S.BranchID=B.BranchID
Group BY S.TTOutTargetTrxnCount,B.BranchCode 

我制作了一个tmp表来寻求帮助

CREATE TABLE #Tempsample
(
    currenct int ,
    targets bigint,
    branchcode nvarchar(128),
    rank int,
    percentage decimal,
    difference int
);


INSERT INTO #Tempsample
  (currenct, targets,branchcode,rank,percentage,difference)
VALUES
  ('131', '2650','EXB', '1','4.94', '2519'),
  ('25', '3500','MHQ', '2','0.71', '3475'),
  ('3', '850','MNM', '3','0.35', '847')

2 个答案:

答案 0 :(得分:1)

你可以试试这样的枢轴:

select 'Targets' as [Header], * from (
    select targets, branchcode from #Tempsample ) a
    pivot (sum(targets) for branchcode in ([EXB], [MHQ], [MNM])) p
union all 
select 'Current' as [Header],* from (
    select currenct, branchcode from #Tempsample ) a
    pivot (sum(currenct) for branchcode in ([EXB], [MHQ], [MNM])) p
union all
select 'Difference' as [Header], * from (
    select difference, branchcode from #Tempsample ) a
    pivot (sum(difference) for branchcode in ([EXB], [MHQ], [MNM])) p
union all
select 'Rank' as [Header], * from (
    select Rank, branchcode from #Tempsample ) a
    pivot (MAX(rank) for branchcode in ([EXB], [MHQ], [MNM])) p

答案 1 :(得分:1)

使用cross apply(values ...)展开您的数据,并使用条件聚合来重新转移您的数据:

select 
    u.Attribute
  , EXB = max(case when branchcode = 'EXB' then value end)
  , MHQ = max(case when branchcode = 'MHQ' then value end)
  , MNM = max(case when branchcode = 'MNM' then value end)
  , Totals = sum(case when u.Attribute = 'rank' then null else value end)
from #tempsample t
  cross apply (values 
      ('currenct',currenct)
    , ('targets',targets)
    , ('difference',difference)
    , ('rank',rank)
    ) u (attribute,value)
group by u.Attribute
order by (case when u.Attribute='rank' then 1 else 0 end)

rextester演示:http://rextester.com/WLES86332

返回:

+------------+------+------+-----+--------+
| Attribute  | EXB  | MHQ  | MNM | Totals |
+------------+------+------+-----+--------+
| currenct   |  131 |   25 |   3 | 159    |
| difference | 2519 | 3475 | 847 | 6841   |
| targets    | 2650 | 3500 | 850 | 7000   |
| rank       |    1 |    2 |   3 | NULL   |
+------------+------+------+-----+--------+