-1

我有以下查询。它给了我一个错误“列 'Sites.IsMobileSite' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。” 对于以下 sql 代码 -

 select max(rc.[name]) [Reseller], max(c.[name]) [Customer],    
        case 
            when max(c.[Url]) is not null then max(c.[URL])
            else 'NA'
        end[URL],   
        case 
            when max(s.[Domain]) is not null then max(s.[Domain])
            else 'NA'
        end[Site Name],
        case 
        when (s.[IsMobileSite]) = 0 then 'No'
        else 'Yes'
        end [Is Mobile Site],
        case 
            when max(s.[CreatedDate]) is not null then max(s.  [CreatedDate])               
        end[Created Date]
    from customers c with(nolock)       
    left outer join Sites s with(nolock) on c.CustomerId = s.CustomerId         
    left outer join customers rc on rc.CustomerId = c.ResellerId
    where c.[name] is not null
    and ( c.customerId is null or rc.CustomerId = c.CustomerId)
    and c.IsActive !='' 
4

1 回答 1

0

我同意 Damien,代码不够清晰,无法显示您正在尝试做什么,并且将每个返回的列都放在最大包装器中并没有任何意义。但是,要删除您的错误,您需要将 IsMobileSite 包装在最大包装器中:

    when ( max(s.[IsMobileSite])) = 0 then 'No'
    else 'Yes'
    end [Is Mobile Site],

或按它分组:

 select max(rc.[name]) [Reseller], max(c.[name]) [Customer],    
    case 
        when max(c.[Url]) is not null then max(c.[URL])
        else 'NA'
    end[URL],   
    case 
        when max(s.[Domain]) is not null then max(s.[Domain])
        else 'NA'
    end[Site Name],
    case 
    when (s.[IsMobileSite]) = 0 then 'No'
    else 'Yes'
    end [Is Mobile Site],
    case 
        when max(s.[CreatedDate]) is not null then max(s.  [CreatedDate])               
    end[Created Date]
from customers c with(nolock)       
left outer join Sites s with(nolock) on c.CustomerId = s.CustomerId         
left outer join customers rc on rc.CustomerId = c.ResellerId
where c.[name] is not null
and ( c.customerId is null or rc.CustomerId = c.CustomerId)
and c.IsActive !='' 
GROUP BY s.[IsMobileSite]

此外,除了所有这些 case 语句之外,coalesce 将完成这项工作,而是从提供给它的列表中返回第一个非 null 项:

coalesce(max(c.[Url]), 'NA') [URL], 

如果不为空,则返回 max(c.[Url]),否则返回 'NA'

如果您只想返回与选择条件匹配的第一行,那么只需执行以下操作:

SELECT  TOP 1
    rc.name Reseller,
    c.name Customer,
    COALESCE(c.Url, 'NA') URL,
    COALESCE(s.domain, 'NA') [Site Name],
    CASE
        WHEN s.IsMobileSite = 0 THEN  'No'
        ELSE 'YES'
    END [Is Mobile Site],
    s.CreatedDate
FROM customers c WITH(nolock)
JOIN Sites s WITH(nolock)
ON c.CustomerId = s.CustomerId    
LEFT JOIN customers rc 
ON rc.CustomerId = c.ResellerId
WHERE c.name IS NOT NULL
AND ( c.customerId is null OR rc.CustomerId = c.CustomerId
AND c.IsActive !=''  
于 2013-11-08T15:05:36.287 回答