使用多个条件多次选择单个字段

时间:2013-07-29 11:04:55

标签: sql sql-server pivot

我需要在下表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条件已经用于Activity'Shearing'。这可能是一项简单的任务,但我是SQL的新手,因此需要帮助!

4 个答案:

答案 0 :(得分: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);

见:

答案 1 :(得分: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 DEMO

答案 2 :(得分: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

答案 3 :(得分:0)

你想要的是SQL中的“Partition By”关键字。 更准确地总和(....)(按活动分区)。 这应该可以解决问题。