SQLServer2008中的透视表
请在SQL server数据透视表中帮助我。我得到的输出如下。现在,我希望在每个日期行下的单独列中显示分配挂起和编码挂起的总计数SQLServer2008中的透视表,sql,sql-server,tsql,pivot,Sql,Sql Server,Tsql,Pivot,请在SQL server数据透视表中帮助我。我得到的输出如下。现在,我希望在每个日期行下的单独列中显示分配挂起和编码挂起的总计数 select ScanDate, filestatus, COUNT(filestatus) as filecount from ScanLog where FileSource = 'ebridge' group by filestatus, ScanDate scandate filestatus filecount 2013-08-0
select ScanDate, filestatus, COUNT(filestatus) as filecount from ScanLog
where FileSource = 'ebridge'
group by filestatus, ScanDate
scandate filestatus filecount
2013-08-01 Allocation Pending 8
2013-08-01 Coding Pending 1
2013-08-02 Allocation Pending 4
2013-08-02 Coding Pending 1
2013-08-03 Allocation Pending 4
2013-08-04 Allocation Pending 18
2013-08-04 Coding Pending 3
2013-08-05 Allocation Pending 6
我使用了以下代码,但出现错误,因为“scandate”不是有效字段。请引导我
select [scandate] from ScanLog
pivot (count(scandate)
for filestatus in ([allocation pending],[coding pending])) as A
where FileSource = 'ebridge'
试试这个查询,
您可以使用左外联接、右外联接或内联接
取决于数据在表中的方式
SELECT frst.scandate
, frst.filestatus
, frst.filecount
, secnd.filestatus
, secnd.filecount1
FROM
(
SELECT scandate
, filestatus
, COUNT(filestatus) AS filecount
FROM ScanLog
WHERE FileSource = 'ebridge'
AND filestatus = 'Allocation Pending'
GROUP BY
filestatus
, scandate
) frst
LEFT OUTER JOIN
(
SELECT scandate
, filestatus
, COUNT(filestatus) AS filecount1
FROM ScanLog
WHERE FileSource = 'ebridge'
AND filestatus = 'Coding Pending'
GROUP BY
filestatus
, scandate
) secnd ON frst.scandate = secnd.scandate
试试这个-
DECLARE @temp TABLE (
ScanDate DATETIME
, FileSource VARCHAR(10)
, FileStatus VARCHAR(30)
, FileCount INT
)
INSERT INTO @temp
VALUES
('2013-08-01', 'ebridge', 'Allocation Pending', 8),
('2013-08-01', 'ebridge', 'Coding Pending', 1),
('2013-08-02', 'ebridge', 'Allocation Pending', 4),
('2013-08-02', 'ebridge', 'Coding Pending', 1),
('2013-08-03', 'ebridge', 'Allocation Pending', 4),
('2013-08-04', 'ebridge', 'Allocation Pending', 18),
('2013-08-04', 'ebridge', 'Coding Pending', 3),
('2013-08-05', 'ebridge', 'Allocation Pending', 6)
SELECT *
FROM (
SELECT scandate, filestatus
FROM @temp
WHERE FileSource = 'ebridge'
) t
PIVOT (
COUNT(scandate)
FOR filestatus IN ([Allocation Pending], [Coding Pending])
) a
您缺少
where FileSource='ebridge'
@Devart,非常感谢您的解决方案。它很好用。只是我改变了Pivot(Count(Filestatus)而不是Count(scandate)。如果这个解决方案完全适合您,请批准它。