如何 Select * 除了一个字段外,所有内容都是不同的

How to Select * Where Everything is Distinct Except One Field

我正在尝试使用下面的代码提取 6 条记录,但在某些情况下信息会更新,因此会提取重复的记录。

我的代码:

SELECT column2, count(*) as 'Count'
FROM ServiceTable p
join HIERARCHY h
on p.LOCATION_CODE = h.LOCATION
where Report_date between '2017-04-01' and '2017-04-30'


and Column1 = 'Issue '
and LOCATION = '8789'

and
( record_code = 'INCIDENT' or
    (
    SUBMIT_METHOD = 'Web' and
    not exists
    (
    select *
    from ServiceTable p2
    where p2.record_code = 'INCIDENT'
        and p2.incident_id = p.incident_id      
        )


    )
)

问题是它拉出了八条记录,而不是六条记录。我只想使用不同的 * 但是 file_date 在重复条目上是不同的:

FILE_DATE     Incident_ID       Column1        Column2
 4/4/17          123              Issue      Service - Red
 4/4/17          123              Issue      Service - Blue
 4/5/17          123              Issue      Service - Red
 4/5/17          123              Issue      Service - Blue

期望的输出是:

  COLUMN2         COUNT
 Service - Red      1
 Service - Blue     1

如有任何帮助,我们将不胜感激!如果您需要任何其他信息,请告诉我。

如果您使用的是聚合函数(计数),则应该对聚合函数中的列 而不是 使用 group by

    SELECT column2, count(*) as 'Count'
    FROM ServiceTable p
    join HIERARCHY h
    on p.LOCATION_CODE = h.LOCATION
    where Report_date between '2017-04-01' and '2017-04-30'
    and Column1 = 'Issue '
    and LOCATION = '8789'
    and
    ( record_code = 'INCIDENT' or
        (
        SUBMIT_METHOD = 'Web' and
        not exists
        (
        select *
        from ServiceTable p2
        where p2.record_code = 'INCIDENT'
            and p2.incident_id = p.incident_id      
            )


        )
    )
    group by column2

如果您将不带聚合函数的原始 select 语句转换为子查询,您可以在不是更改日期的值上区分它,然后从那里 select 一个 COUNT。不要忘记最后的 GROUP BY 子句。

SELECT Column2, COUNT(Incident_ID) AS Service_Count
FROM (SELECT DISTINCT Incident_ID, Column1, Column2
  FROM ServiceTable p
  JOIN HIERARCHY h ON p.LOCATION_CODE = h.LOCATION
  WHERE Report_date BETWEEN '2017-04-01' AND '2017-04-30'
  AND Column1 = 'Issue '
  AND LOCATION = '8789'
  AND
  ( record_code = 'INCIDENT' or
      (
      SUBMIT_METHOD = 'Web' and
      NOT EXISTS
      (
        SELECT *
        FROM ServiceTable p2
        WHERE p2.record_code = 'INCIDENT'
            AND p2.incident_id = p.incident_id)
      )
  )
)
GROUP BY Column2

此外,如果您要联接表,最好完全限定您正在 select 的字段。示例:p.Column2,p.Incident_ID,h.LOCATION。这样,即使您的不同领域也更容易了解它们的来源以及它们之间的关系。

最后,别忘了COUNT是保留字。我相应地修改了你的别名。