17
TRANSFORM Avg(CASE WHEN [temp].[sumUnits] > 0 
                   THEN [temp].[SumAvgRent] / [temp].[sumUnits] 
                   ELSE 0 
              END) AS Expr1
SELECT [temp].[Description]
  FROM [temp] 
GROUP BY [temp].[Description]
PIVOT [temp].[Period];

需要将此查询转换为 sql server

我已阅读所有其他帖子,但无法将其转换为相同的

4

2 回答 2

21

PIVOT这是使用表运算符的等效版本:

SELECT *
FROM
(
  SELECT 
    CASE 
      WHEN sumUnits > 0 
      THEN SumAvgRent / sumUnits ELSE 0 
  END AS Expr1,
  Description,
  Period
  FROM temp
) t
PIVOT
(
  AVG(Expr1)
  FOR Period IN(Period1, Period2, Period3)
) p;

SQL 小提琴演示

例如,这将为您提供:

| DESCRIPTION | PERIOD1 | PERIOD2 | PERIOD3 |
---------------------------------------------
|          D1 |      10 |       0 |      20 |
|          D2 |     100 |    1000 |       0 |
|          D3 |      50 |      10 |       2 |

请注意,当使用 MS SQL ServerPIVOT表运算符时,您必须输入透视列的值。然而,在 MS Access 中,这是 do 的工作TRANSFORMPIVOT它动态地获取旋转列的值。在这种情况下,您必须使用运算符动态地执行此PIVOT操作,如下所示:

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

SELECT @cols = STUFF((SELECT distinct 
                        ',' +
                        QUOTENAME(Period)
                FROM temp
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'');



SET @query =  ' SELECT Description, ' + @cols + '
    FROM 
    (
      SELECT 
        CASE 
          WHEN sumUnits > 0 
          THEN SumAvgRent / sumUnits ELSE 0 
      END AS Expr1,
      Description,
      Period
      FROM temp
    ) t
    PIVOT
    (
      AVG(Expr1)
      FOR Period IN( ' + @cols + ') 
    ) p ';



Execute(@query);

更新的 SQL Fiddle 演示

这应该会给您相同的结果:

| DESCRIPTION | PERIOD1 | PERIOD2 | PERIOD3 |
---------------------------------------------
|          D1 |      10 |       0 |      20 |
|          D2 |     100 |    1000 |       0 |
|          D3 |      50 |      10 |       2 |
于 2012-12-19T13:45:05.200 回答
-2
TRANSFORM SUM(s2+s1) 
SELECT PlanoContas.Conta AS Conta,
SPACE(LEN(PlanoContas.Conta)/2) + PlanoContas.Extenso AS Extenso,
PlanoContas.Tipo,SUM(s2+s1) AS [01/04/14] 
FROM PlanoContas 
INNER JOIN TEMP ON 
PlanoContas.Conta=LEFT(Temp.Conta,LEN(PlanoContas.Conta)) 
WHERE LEN(PlanoContas.Conta)<=16 AND (s1<>0 OR s2<>0) 
GROUP BY PlanoContas.Conta,Extenso,Tipo 
ORDER BY PlanoContas.Conta PIVOT Filial
于 2014-09-02T14:19:32.373 回答