使用PHP和SQL合并动态列

vawmfj5a  于 2023-09-29  发布在  PHP
关注(0)|答案(1)|浏览(97)

WAMPserver下的最新PHP
SQL Server 2005
用户向my.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
hujrc8aj

hujrc8aj1#

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

相关问题