使用 PHP 和 SQL 合并的动态列

问题描述 投票:0回答:1

WAMPserver下的最新PHP

SQL Server 2005

用户将两个变量传递到我的 .php 报告页面,$thedate1 和 $thedate2,它们是我想要从数据库检索的值的开始和结束日期时间戳。我聚合数据并将其转换为 SUM 函数以获得我想要的报告,但我不知道如何包含日期范围内的所有天数以在最终报告中显示为单独的列。

因此,如果 $thedate1='2012-02-20' 和 $thedate2='2012-02-28' 我希望在最终报告中动态创建中间每一天(含)的列。目前我必须手动将日期添加到查询中,但我希望有一种方法可以自动添加它们。

有什么想法吗?

WITH T 
AS(
    SELECT CorrectionUser, CorrectionsCount, 
    DATEADD(dd, DATEDIFF(d, 0, DateHourCorrected), 0) as [DATE]
    FROM ISIImageCorrections
)
SELECT CorrectionUser AS [Employee], 
       COALESCE([2012-02-20], 0) AS [2012-02-20],
       COALESCE([2012-02-21], 0) AS [2012-02-21],
       COALESCE([2012-02-22], 0) AS [2012-02-22]
FROM T
PIVOT(SUM(CorrectionsCount) FOR [Date] IN([2012-02-20], [2012-02-21], [2012-02-22]))
AS P
ORDER BY CorrectionUser
php sql sql-server-2005 dynamic
1个回答
0
投票
if OBJECT_ID('tempdb..#t1') is not null DROP TABLE #t1;
CREATE TABLE #t1 (d date NOT NULL);

DECLARE @start date;
SET @start = '2012-04-05';
DECLARE @end date;
SET @end = '2012-04-25';
WHILE (@start <= @end)
begin
    INSERT INTO #t1 VALUES(DATEADD(day, 1, @start));
    SET @start = DATEADD(day, 1, @start);
end;

SELECT * FROM #t1;
DROP TABLE #t1
© www.soinside.com 2019 - 2024. All rights reserved.