是否可以使用Pivot进行相同的查询?

时间:2016-10-09 02:25:41

标签: sql-server tsql

我有一张桌子

CREATE TABLE #FinalRates
(
id int primary key identity(1,1),
RateDesc nvarchar(50),
Amt decimal(18,2)
)

insert into #FinalRates values('100',200)
insert into #FinalRates values('100',300)
insert into #FinalRates values('50-80',100)
insert into #FinalRates values('50-80',300)
insert into #FinalRates values('30-50',500)
insert into #FinalRates values('30-50',250)

寻找输出

RateDesc    Amount1 Amount2
100          200    300
50-80        100    300
30-50        500    250 

我这样做了

;with cte as(
select 
                RateDesc 
                ,Amounts=
                      STUFF((Select ','+ cast(cast(Amt as int) as varchar(10))
                      from #FinalRates T1
                       where T1.RateDesc=T2.RateDesc
                       FOR XML PATH('')),1,1,'') 
from #FinalRates T2
group by T2.RateDesc
)

select 
        RateDesc,
        Amount1 = PARSENAME(REPLACE(Amounts,',','.'),2),
        Amount2 = PARSENAME(REPLACE(Amounts,',','.'),1)
From Cte

Drop table #FinalRates

使用PIVOT可以做同样的事吗?

提前致谢。

2 个答案:

答案 0 :(得分:3)

那太复杂了。怎么样?

pivot

您可以使用id类似的方法,但条件聚合通常表现更好。

另外,如果您知道select ratedesc, max(case when id % 2 = 1 then amt end) as Amount1, max(case when id % 2 = 0 then amt end) as Amount2 from #finalrates fr group by ratedesc; 中没有漏洞,则可以执行以下操作:

{{1}}

答案 1 :(得分:1)

使用PIVOT,

假设每个RateDesc都有2 Amt。

<html ng-app>
    <head>
     <script src =  
     "https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js">   
      </script>
      </head>
      <body>
      <div class = "basic_class" ng-controller = "write_controller">
      <ul>
        <li ng-repeat = "todo in todos"><input type = "checkbox" ng-model  
         ="todo.done">{{todo.text}}</input></li>
      </ul>
      <input type = "text"
        placeholder = "please add data here"
        ng-model="todopush">
      </input>
      <input type = "button" ng-click ="addtodo()" value ="Click me!!"></input>
      <input type = "button" ng-click = "delete()" ng-model="remove" value =  
       "remove!"></input>
      </div>
</body>
</html>