3

我需要从下表 PLE 的每个活动中生成一个项目明智的表面积

Activity    Posting Date    Surface Area  Project
---------------------------------------------------------------------
Shearing     01-04-2013     2.34          A   
Bending      01-04-2013     2.34          A 
Assembly     02-04-2013     2.34          B
PC           02-04-2013     5.34          B  
Infill       05-04-2013     5.34          C

我正在尝试这样做。

SELECT DISTINCT Project,sum(Project.[Surface Area]) AS TotalShearing 
FROM PLE
WHERE ([Posting Date] BETWEEN @StartDate AND @EndDate)
  AND (Activity = Shearing)
GROUP BY Project

现在我想TotalBending, TotalAssembly在右边的列中显示等等TotalShearing。但不知道如何获取它们,因为 WHERE 条件已用于活动“剪切”。这可能是一项简单的任务,但我是 SQL 新手,因此需要帮助!

4

4 回答 4

1

使用PIVOT表运算符:

SELECT *
FROM 
(
  SELECT Activity, [Surface Area], project
  FROM PLE
) AS t
PIVOT
(
  sum([Surface Area])
  FOR Activity IN ([Shearing], 
                   [Bending], 
                   [Assembly], 
                   [PC],
                   [Infill])
) AS p;

如果您想为每个数字动态执行此操作,Activity则必须使用如下动态 SQL:

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


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

SELECT @query = 'SELECT *
FROM 
(
  SELECT Activity, [Surface Area], project
  FROM PLE
) AS t
PIVOT
(
  sum([Surface Area])
  FOR Activity IN (' + @cols + ')
) AS p';

execute(@query);

看到这个:

于 2013-07-29T11:16:26.373 回答
0

你想要的是 SQL 中的“Partition By”关键字。更准确地说,Sum(....) over(Partition by Activity)。这应该够了吧。

于 2013-07-29T11:33:08.723 回答
0

尝试这样的事情:

SELECT Project
    ,sum(CASE WHEN Activity = 'Shearing' THEN [Surface Area] ELSE 0 END) AS TotalShearing 
    ,sum(CASE WHEN Activity = 'Bending' THEN [Surface Area] ELSE 0 END) AS TotalBending
    ,sum(CASE WHEN Activity = 'Assembly' THEN [Surface Area] ELSE 0 END) AS TotalAssembly
    ,sum(CASE WHEN Activity = 'PC' THEN [Surface Area] ELSE 0 END) AS TotalPC
    ,sum(CASE WHEN Activity = 'Infill' THEN [Surface Area] ELSE 0 END) AS TotalInfill
WHERE ([Posting Date] BETWEEN @StartDate AND @EndDate)
FROM PLE
GROUP BY Project

SQLFiddle 演示

于 2013-07-29T11:15:52.470 回答
0
SELECT DISTINCT Project,
sum(if(Activity = 'Shearing', Project.[Surface Area],0) AS Shearing ,
sum(if(Activity = 'Bending', Project.[Surface Area],0) AS TotalBending, 
sum(if(Activity = 'Assembly', Project.[Surface Area],0) AS TotalAssembly
FROM PLE
WHERE ([Posting Date] BETWEEN @StartDate AND @EndDate)

GROUP BY Project
于 2013-07-29T11:18:16.703 回答