我确实有一行表(Type = E)与另一行有关。 我编写了查询以返回那些相关行的COUNT。问题是没有明确的关系(比如ID列可以清楚地说明哪一行与其他行相关)。因此,我试图在WHERE子句中找到基于多个条件的关系。
问题是在少数情况下,A列和B列可能为NULL(对于TYPE ='M'的记录)。在这种情况下,我想忽略这个条件,所以它只使用前3个条件来确定关系。
我已经尝试了CASE声明,但没有按预期工作:
SELECT [T1].[ID],[T1].[AlphaId],[T1].[Type],[T1].[A],[T1].[B],[T1].[Date],[T1].[ServiceID]
,( SELECT COUNT(*)
FROM MyTable T2
WHERE [T1].[AlphaId]=[T2].[AlphaId] AND
[T1].[Date]=[T2].[Date] AND
[T1].[ServiceID]=[T2].[ServiceID] AND
[T2].[A]=CASE WHEN [T2].[A] IS NULL THEN NULL ELSE [T1].[A] END AND
[T2].[B]=CASE WHEN [T2].[B] IS NULL THEN NULL ELSE [T1].[B] END AND
[T2].[Type]='M'
) as TotalCount
FROM MyTable T1
WHERE [T1].[Type] = 'E'
我不能忽视这个条件,因为在某些情况下,Date,ServiceID可能是相同的,但它是A,B,它们不同。幸运的是,A,B是NULL,它是Date,ServiceID,它们区别于这两个记录。
http://sqlfiddle.com/#!3/c98db/1
非常感谢提前。
答案 0 :(得分:0)
您可以加入表并使用COUNT和GROUP BY来获取计数。然后,如果它们相等或为NULL,则可以加入[A]和[B]。
SELECT [T1].[ID],[T1].[AlphaId],[T1].[Type],[T1].[A],[T1].[B],[T1].[Date],[T1].[ServiceID], count([T2].[ID])
FROM MyTable T1
INNER JOIN MyTable T2 ON [T1].[AlphaId]=[T2].[AlphaId] AND
[T1].[Date]=[T2].[Date] AND
[T1].[ServiceID]=[T2].[ServiceID] AND
([T2].[A]= [T1].[A] OR [T2].[A] IS NULL )AND
([T2].[B]= [T1].[B] OR [T2].[B] IS NULL )AND
[T2].[Type] <> [T1].[Type]
WHERE [T1].[Type] = 'E'
GROUP BY [T1].[ID],[T1].[AlphaId],[T1].[Type],[T1].[A],[T1].[B],[T1].[Date],[T1].[ServiceID]