[英]Pivot/Cross tab results on PHP/SQL query
Running most recent version of PHP under most recent build of WAMPserver. 在最新版本的WAMPserver下运行最新版本的PHP。
Database is SQL Server 2005 数据库是SQL Server 2005
Here is the query I am currently running that works. 这是我当前正在运行的查询。 What I want to do is change the output from: 我想做的是更改输出:
CorrectionsCount , Employee , Date
1 , Joe , 02/12/2012
31 , Barbara , 02/13/2012
12 , Paula , 02/16/2012
To something like this 对于这样的事情
[EMPLOYEE NAME], 02/12/2012, 02/13/2012, 02/16/2012
Joe , 31 , 0 , 0
Barbara , 0 , 31 , 0
Paula , 0 , 0 , 12
Code: 码:
<?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 and $thedate2 are variables being POSTed to this page by a calendar picker from another PHP page. $ thedate1和$ thedate2是由日历选择器从另一个PHP页面发布到此页面的变量。
UPDATE: I tried running the COALESCE function described below, but it generates a syntax error near the keyword 'FROM' (the second instance of "FROM" in this statement). 更新:我尝试运行下面描述的COALESCE函数,但是它在关键字“ FROM”(此语句中“ FROM”的第二个实例)附近生成了语法错误。 Am I inputting it properly? 我输入正确吗?
$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"');
Here I am using SUM
, choose any aggregate function of your liking: 在这里,我使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.