0

我编写了一个返回多个列的查询。其中一列包含重复条目。

FAULT_SHORT_NAME

ATM DOWN DUE TO LINK PROBLEM
ATM DOWN DUE TO LINK PROBLEM
ALL CASSETTES FAULTED
ALL CASSETTES FAULTED
ATM IS MARK DOWN
ATM IS MARK DOWN

现在我想以这样的方式修改我的查询,它会显示我的值计数为

ATM DOWN DUE TO LINK PROBLEM ALL CASSETTES FAULTED  ATM IS MARK DOWN
2                             2                         2

可能有不同的“FAULT_SHORT_NAME”值,所以不能对它们进行硬编码。我的原始查询是

      Select * From ATMStatus S Left Join ATM A on S.ATM=A.Code 
          Left Join EventMsg E On S.Fault=E.Code 
          Where A.ATMStatus=0 AND S.TicketBooked <> 0

FAULT_SHORT_NAME 是表“EventMsg”的列

4

1 回答 1

4

看起来您想要 aPIVOT因为您希望将值作为列而不是行。有两种方法可以做到这一点,静态或动态枢轴。

静态枢轴,您对列的值进行硬编码:

SELECT *
FROM
(
    Select * 
    From ATMStatus S 
    Left Join ATM A 
        on S.ATM=A.Code 
    Left Join EventMsg E 
        On S.Fault=E.Code 
    Where A.ATMStatus=0 
        AND S.TicketBooked <> 0
) x
PIVOT
(
    count(*)
    for FAULT_SHORT_NAME in ([ATM DOWN DUE TO LINK PROBLEM], 
        [ALL CASSETTES FAULTED], [ATM IS MARK DOWN])
) p

Dynamic Pivot,列在运行时生成:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(FAULT_SHORT_NAME) 
                    from EventMsg
                    FOR XML PATH(''), TYPE
                    ).value('.', 'NVARCHAR(MAX)') 
                ,1,1,'')
set @query 
      = 'SELECT ' + @cols + ' from 
         (
            Select * 
            From ATMStatus S 
            Left Join ATM A 
                on S.ATM=A.Code 
            Left Join EventMsg E 
                On S.Fault=E.Code 
            Where A.ATMStatus=0 
                AND S.TicketBooked <> 0
         ) x
         pivot 
         (
            count(*)
            for FAULT_SHORT_NAME in(' + @cols + ')
         ) p '

execute(@query)

两者都会产生相同的结果。如果您提供有关表格和一些示例数据的其他详细信息,那么我可以提供一个更准确的示例。

于 2012-08-23T14:21:57.923 回答