gpt4 book ai didi

sql - 如何选择 * 除一个字段外,其他所有内容都不同的地方

转载 作者:行者123 更新时间:2023-12-01 04:48:48 25 4
gpt4 key购买 nike

我正在尝试使用下面的代码提取 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     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

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

最佳答案

如果您将没有聚合函数的原始选择语句转换为子查询,您可以在不是更改日期的值上区分它,然后从那里选择一个 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

此外,如果您要加入表格,最好完全限定您选择的字段。示例:p.Column2、p.Incident_ID、h.LOCATION。这样,即使是您不同的领域也更容易了解它们来自何处以及它们之间的关系。

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

关于sql - 如何选择 * 除一个字段外,其他所有内容都不同的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43920647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com