Pivot / Cross选项卡导致PHP / SQL查询

时间:2012-02-28 16:41:22

标签: php sql sql-server sql-server-2005 pivot

在最新版本的WAMPserver下运行最新版本的PHP。

数据库是SQL Server 2005

这是我目前正在运行的查询。我想要做的是改变输出:

CorrectionsCount , Employee  , Date    
1                , Joe       , 02/12/2012
31               , Barbara   , 02/13/2012    
12               , Paula     , 02/16/2012

这样的事情

[EMPLOYEE NAME], 02/12/2012,    02/13/2012,    02/16/2012    
Joe              , 31         , 0              , 0    
Barbara          , 0          , 31             , 0   
Paula            , 0          , 0              , 12

代码:

<?php

// connect to DSN 
$DP2connect = odbc_connect("DB", "USER", "PWORD") or die ("Could not connect to 

server");

$DP2query = "
SELECT SUM(CorrectionsCount),CorrectionUser,
convert(char(10), DateHourCorrected, 120)
FROM ISIImageCorrections
WHERE DateHourCorrected BETWEEN '$theDate1' AND '$theDate2'
GROUP BY CorrectionsCount,CorrectionUser,DateHourCorrected
";


$DP2result2 = odbc_exec($DP2connect, $DP2query);

odbc_result_all($DP2result2, 'id="results"');
?>

$ thedate1和$ thedate2是由另一个PHP页面的日历选择器发布到此页面的变量。

更新:我尝试运行下面描述的COALESCE函数,但它在关键字“FROM”(此语句中的“FROM”的第二个实例)附近生成语法错误。我输入得当吗?

$DP2connect = odbc_connect("dp2_database", "DP2", "DP2Express!") or die ("Could not connect to 

server");

$DP2query = 
"WITH T 
AS(
    SELECT CorrectionUser, CorrectionsCount, DateHourCorrected
    FROM ISIImageCorrections
)
SELECT CorrectionUser, 
       COALESCE([02/12/2012], 0) AS [02/12/2012],
       COALESCE([02/13/2012], 0) AS [02/13/2012],
       COALESCE([02/16/2012], 0) AS [02/16/2012],
FROM T
PIVOT(SUM(CorrectionsCount) FOR [Date] IN([02/12/2012], [02/13/2012], [02/16/2012])) AS P";


$DP2result2 = odbc_exec($DP2connect, $DP2query);

odbc_result_all($DP2result2, 'id="results"');

1 个答案:

答案 0 :(得分:0)

我在这里使用SUM,选择你喜欢的任何聚合函数:

WITH T AS(
    SELECT Employee, CorrectionsCount, [Date]
    FROM @yourTable
)
SELECT Employee, 
       COALESCE([02/12/2012], 0) AS [02/12/2012],
       COALESCE([02/13/2012], 0) AS [02/13/2012],
       COALESCE([02/16/2012], 0) AS [02/16/2012]
FROM T
PIVOT(SUM(CorrectionsCount) FOR [Date] 
      IN([02/12/2012], [02/13/2012], [02/16/2012])) AS P;