为了账号安全,请及时绑定邮箱和手机立即绑定

理解T-SQL中的枢轴函数

理解T-SQL中的枢轴函数

理解T-SQL中的枢轴函数我对SQL非常陌生。我有一张这样的桌子:ID | TeamID | UserID | ElementID | PhaseID | Effort-----------------------------------------------------1  |   1    |  1      |   3       |  5     |   6.742  |   1    |  1      |   3       |  6     |   8.253  |   1    |  1      |   4       |  1     |   2.234  |   1    |  1      |   4       |  5     |   6.85  |   1    |  1      |   4       |  6     |   1.5我被告知要得到这样的数据ElementID | PhaseID1 | PhaseID5 | PhaseID6--------------------------------------------    3     |   NULL   |   6.74   |   8.25    4     |   2.23   |   6.8    |   1.5我知道我需要使用枢轴函数。但不明白。如果有人能在上述情况下解释它,那将是很有帮助的。(如果有的话)。
查看完整描述

3 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

这是一个非常基本的枢轴例子,请仔细看一遍。

Sqlserver-枢轴和UNPIVOT表示例

下面是产品表的上述链接中的示例:

SELECT PRODUCT, FRED, KATEFROM (SELECT CUST, PRODUCT, QTYFROM Product) up PIVOT (SUM(QTY) FOR CUST IN (FRED, KATE)) AS pvtORDER BY PRODUCT

呈现:

 PRODUCT FRED  KATE --------------------
 BEER     24    12
 MILK      3     1
 SODA   NULL     6
 VEG    NULL     5

类似的例子可以在博客文章中找到。SQL Server中的枢轴表。一个简单的样本


查看完整回答
反对 回复 2019-07-12
?
MMTTMM

TA贡献1869条经验 获得超4个赞

   SELECT <non-pivoted column>,

    [first pivoted column] AS <column name>,

    [second pivoted column] AS <column name>,

    ...

    [last pivoted column] AS <column name>

FROM

    (<SELECT query that produces the data>)

    AS <alias for the source query>

PIVOT

(

    <aggregation function>(<column being aggregated>)

FOR

[<column that contains the values that will become column headers>]

    IN ( [first pivoted column], [second pivoted column],

    ... [last pivoted column])

) AS <alias for the pivot table>

<optional ORDER BY clause>;


USE AdventureWorks2008R2 ;

GO

SELECT DaysToManufacture, AVG(StandardCost) AS AverageCost 

FROM Production.Product

GROUP BY DaysToManufacture;


    DaysToManufacture          AverageCost

0                          5.0885

1                          223.88

2                          359.1082

4                          949.4105


    -- Pivot table with one row and five columns

SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days, 

[0], [1], [2], [3], [4]

FROM

(SELECT DaysToManufacture, StandardCost 

    FROM Production.Product) AS SourceTable

PIVOT

(

AVG(StandardCost)

FOR DaysToManufacture IN ([0], [1], [2], [3], [4])

) AS PivotTable;





Here is the result set.

Cost_Sorted_By_Production_Days    0         1         2           3       4       

AverageCost                       5.0885    223.88    359.1082    NULL    949.4105



查看完整回答
反对 回复 2019-07-12
  • 3 回答
  • 0 关注
  • 464 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信