评估&&条件仅适用于具有匹配时间的行

时间:2014-12-03 00:44:18

标签: sql sql-server sql-server-2014

以下是我的疑问:

SELECT DISTINCT 
               SC.Feature, 
               CASE WHEN SA.Target > ANY(SELECT SA.Availability) THEN 0 ELSE 1 END AS IsAvailable,
               SA.Date AS DateTime

FROM           dbo.ServiceAvailability AS SA LEFT OUTER JOIN
               dbo.ServiceCatalog AS SC ON SA.ServiceID = SC.ServiceID

我的输出结果是这种形式:

Feature    IsAvailable    DateTime
-------------------------------------------------
  F1            0         2014-11-01 07:00:00.000 
  F1            1         2014-11-01 07:00:00.000

如何将查询更改为AND输出,以便我将这两行合并到下面?

Feature    IsAvailable    DateTime
-------------------------------------------------
  F1            0         2014-11-01 07:00:00.000 

编辑:如果IsAvailable值均为1,那么它们ANDIsAvailable = 1合并为{{1}}

3 个答案:

答案 0 :(得分:1)

我认为这应该有效:

SELECT
               SC.Feature, 
               CASE WHEN sum(
                       CASE WHEN SA.Target > ANY(SELECT SA.Availability) 
                          THEN 1 
                          ELSE 0 
                       END) >= 1 
                    THEN 0 
                    ELSE 1 
               END AS IsAvailable,
               SA.Date AS DateTime

FROM           dbo.ServiceAvailability AS SA 
LEFT JOIN      dbo.ServiceCatalog AS SC ON SA.ServiceID = SC.ServiceID
GROUP BY       SC.Feature, 
               SA.Date

我颠倒了内部CASE语句,因此0现在是1,反之亦然。然后我们可以将按组列分组的总和相加,如果总和大于或等于1那么至少有一个1(实际上是0!),因此操作的结果为0;否则他们都是0(实际上是1),结果应该是1

编辑:响应“无法对包含聚合或子查询的表达式执行聚合函数” - 我没有意识到这是一个限制。我已重新排列查询以首先执行子查询,然后对该数据集进行分组。希望这有效。我认为现在发生的事情还有点清楚。

SELECT
    Feature,
    CASE WHEN sum(IsNotAvailable) >= 1 
        THEN 0 
        ELSE 1 
    END AS IsAvailable,
    [DateTime]
FROM (
    SELECT      
                   SC.Feature,                
                   CASE WHEN SA.Target > ANY(SELECT SA.Availability) 
                      THEN 1 
                      ELSE 0 
                   END AS IsNotAvailable,
                   SA.Date AS DateTime    
    FROM           dbo.ServiceAvailability AS SA 
    LEFT JOIN      dbo.ServiceCatalog AS SC ON SA.ServiceID = SC.ServiceID
) x
GROUP BY       x.Feature, 
               x.[DateTime]

答案 1 :(得分:0)

对于两个操作数之间的,如果只有一个操作数的值 0 ,结果将 0 所以我认为这将解决你的问题:

select distinct * 
 from (SELECT DISTINCT 
           SC.Feature, 
           CASE WHEN SA.Target > ANY(SELECT SA.Availability) THEN 0 ELSE 1 EN
 IsAvailable,
           SA.Date AS DateTime

 FROM           dbo.ServiceAvailability AS SA LEFT OUTER JOIN
           dbo.ServiceCatalog AS SC ON SA.ServiceID = SC.ServiceID) 
 where IsAvailable=0 

答案 2 :(得分:0)

尝试从原始查询中选择不同的行

select distinct * 
from (SELECT 
       SC.Feature, 
       CASE WHEN SA.Target > ANY(SELECT SA.Availability) THEN 0 ELSE 1 EN
IsAvailable,
       SA.Date AS DateTime

 FROM           dbo.ServiceAvailability AS SA LEFT OUTER JOIN
       dbo.ServiceCatalog AS SC ON SA.ServiceID = SC.ServiceID)