对同一字段计算两次不同的次数,并且两次评估都需要一定的计数

问题描述 投票:0回答:1

这是现有查询的布局,它确实有效,但需要稍微调整才能更准确。
当前编写的此查询会在 4 种不同文档类型的总计数为 2 或更高时返回记录。

SELECT TOP (100)
      KeyField1
      ,Field2
      ,Field3
      ,Field4
      ,Field5
      ,Field6
  FROM [Database1].[dbo].[View1]
  where Status in ('A','B')
  and Field3 like 'XYZ%'
  and KeyField1 in
              (select KeyField1
              from [Database2].[dbo].[View2]
              where DocumentType in (415,486,483,452)  --415 A, 486 I, 483 S, 452 P
              group by KeyField1
              having COUNT(DocumentType)>=2)

我试图修复/改变的是:

  1. 我需要单独数486。并且这个计数必须是 1 或更大。
  2. 另外我还需要单独统计 415,483,452 条记录,并且该计数也必须为 1 或更大。
  3. 总共,如果 Count of 486 >=1 AND Count of (415,483,452) >=1,则查询应返回符合此条件的记录。

注:415,483,452 本身的计数可能是 2 或更多。但如果 486 的计数为 0,则不应返回具有这些计数的记录。反之亦然,如果 486 的计数为 1 或 2 或 3(该字段也可以大于 1),但如果 415,483,452 的计数 = 0,则查询也不应返回该记录。

我尝试了以下方法但没有成功...

where 
(   DocumentType = 486
    group by KeyField1
    having COUNT(DocumentType)>=1)
and
    DocumentType in (415,483,452) Order
    group by KeyField1
    having COUNT(DocumentType)>=1)
)

对 WHERE 子句进行此更改后,我收到错误消息:

关键字“group”附近的语法不正确。

sql-server count
1个回答
0
投票

也许这对你有用。请注意,以下查询尚未经过测试,仅通过此服务进行验证。

SELECT TOP (100)
      KeyField1
      ,Field2
      ,Field3
      ,Field4
      ,Field5
      ,Field6
FROM [Database1].[dbo].[View1]
WHERE Status IN ('A','B')
AND Field3 LIKE 'XYZ%'
AND KeyField1 IN (
  SELECT
    KeyField1,
    SUM(CASE
      WHEN DocumentType IN (415,486,483,452) THEN 1,
      ELSE 0
    END
    ) AS TmpCounter
  FROM [Database2].[dbo].[View2]
  WHERE DocumentType IN (415,486,483,452)  --415 A, 486 I, 483 S, 452 P
  GROUP BY KeyField1
  HAVING TmpCounter >= 2
)
© www.soinside.com 2019 - 2024. All rights reserved.