从列计算不同的值

时间:2012-08-23 14:15:33

标签: sql sql-server

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

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”

的列

1 个答案:

答案 0 :(得分:4)

看起来您需要PIVOT,因为您希望将值作为列而不是行。有两种方法可以做静态或动态数据透视。

Static Pivot,您对列的值进行硬编码:

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)

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