怎么做像SQL中的转置?

时间:2016-08-03 12:24:12

标签: sql sql-server tsql

我是SQL新手,我刚刚改变工作,我需要经常使用SQL。

以前,我曾经使用Excel,我可以通过使用数据透视表轻松完成从图1到图2的以下转换

enter image description here

enter image description here

我想在原始数据源上工作,如图1所示, 并在图2中添加一些新列,这些列对应于维度“客户类型”中的每种类型。

我想知道如何在SQL中实现这一点。

4 个答案:

答案 0 :(得分:3)

您正在寻找PIVOT query 链接中的示例非常自我解释;你做这样的事情:

SELECT Brand, Shop, Adult, SeniorCitizen, Student
FROM YourTable
PIVOT (
    SUM(CostOfPurchase) FOR CustomerType IN (Adult, SeniorCitizen, Student)
)

答案 1 :(得分:0)

SELECT brand, shop, 
MAX(CASE WHEN [Customer Type] = 'Adult' THEN [Cost of purchase] ELSE 0 END) AS adult, 
MAX(CASE WHEN [Customer Type] = 'Senior Citizen' THEN [Cost of purchase] ELSE 0 END) AS [senior],
MAX(CASE WHEN [Customer Type] = 'Student' THEN [Cost of purchase] ELSE 0 END) AS sutudent FROM table1
GROUP BY brand, shop

答案 2 :(得分:0)

试试这个

 protected void onPostExecute(List<Address> addresses) {
      if(addresses==null || addresses.size()==0){
    Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
return; // ADD RETURN HERE
// Your code will go beyond toast and NPE
 }
...

如果值是动态的,您可以尝试http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx

答案 3 :(得分:0)

使用PIVOT和动态SQL的另一种方法(如果添加了新的[Customer Type],将节省编辑查询的时间):

DECLARE @cols nvarchar(max),
        @query nvarchar(max)

SELECT @cols = STUFF((
SELECT DISTINCT ','+QUOTENAME([Customer Type]) 
FROM YourTable
FOR XML PATH('')
),1,1,'')

SELECT @query = '
SELECT  *
FROM YourTable
PIVOT (
    SUM([Cost of purchase]) FOR [Customer Type] IN ('+@cols+')
) as pvt
ORDER BY Brand, Shop'

EXEC sp_executesql @query

输出:

Brand   Shop    Adult   Senior Citizen  Student
AAA     1       32343   32288           29618
AAA     2       36209   29060           26354
AAA     3       29902   11137           46743
BBB     1       33625   411127          30001
BBB     2       43168   18657           18243
BBB     3       14951   22626           23542
CCC     1       22194   41338           45287
CCC     2       38443   39329           10384
CCC     3       27422   29866           42628