2

请在 SQL Server PIVOT Table 中帮助我。我得到了如下所示的输出。现在我想要在每个日期行下的单独列中分配待处理和编码待处理的总数。

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'
4

2 回答 2

3

试试这个——

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
于 2013-08-14T14:05:16.493 回答
2

试试这个查询, you may use left outer , right outer join or inner join取决于你的表中的数据

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
于 2013-08-14T14:02:39.600 回答