尽管使用了DISTINCT子句,但视图中的结果重复

时间:2014-07-10 13:56:31

标签: sql sql-server

我在使用这个特定的SQL查询时遇到了一些麻烦 我正在创建一个视图,显示每种类型的用户,金额 他们报告的问题,问题解决的最早日期, 以及问题仍未解决的最早日期 这是第一部分,因为我需要它不能正常工作。尽管 使用DISTINCT子句,查询返回类似这样的内容

Admin,0,08 / 21 / 1995,03 / 05/1991 Admin,14,48 / 21 / 1995,03 / 05/1991

等等,用于其他用户类型。 有没有办法过滤这些结果,以便列值为0 结果不会出现?或者行为与我的方式有关 进行查询?

视图代码是这样的:

select distinct u.user_cod_type,
(select count(p.problem_id)
from problems p
        where u.user_id = p.user_id) as problemquantity, 
(select min(problem_solved_date)
from problems p1, problem_history h
        where p1.problem_id=h.problem_id
and problem_solved_date is not null) as solvedolderdate, 
(select min(problem_date)
         from problems p2, problem_history h1
        where p2.problem_id=h1.problem_id
    and problem_solved_date is null) as unsolvedolderdate
 from users u

表架构:

problems
(
  problem_id      integer  not null identity(1,1)
  equipment_id    integer  not null,
  user_id         integer  not null,
  problem_date    datetime not null,
  problem_descrip varchar(255)
)

users
(user_id             integer identity (1,1) not null,
user_cod_type         char(20)     not null,
userfname             varchar(80),
userlname             varchar(80),
usermail              varchar(80),
useraddress           varchar(255)
)

problem_history
(problem_history_id integer identity (1,1) not null,
problem_priority char(20) not null,
problem_id integer not null,
problem_status_code char(20) not null,
problem_personnel_id integer not null,
problem_solved_date datetime)

提前致谢

1 个答案:

答案 0 :(得分:0)

这是您的查询,重新格式化并使用显式连接:

select distinct u.user_cod_type,
       (select count(p.problem_id)
        from problems p
        where u.user_id = p.user_id
       ) as problemquantity,
       (select min(problem_solved_date)
        from problems p1 join
             problem_history h
             on p1.problem_id=h.problem_id and
                problem_solved_date is not null
       ) as solvedolderdate,
       (select min(problem_date)
        from problems p2 join
             problem_history h1
             on p2.problem_id=h1.problem_id and problem_solved_date is null
       ) as unsolvedolderdate
 from users u;

这是造成重复的原因:

select distinct u.user_cod_type,
       (select count(p.problem_id)
        from problems p
        where u.user_id = p.user_id
--------------^
       ) as problemquantity,

您正在寻找不同的代码,但相关性是user_id。据推测,多个用户具有相同的代码。因此,您为每个用户分别获取一行。一种解决方案是使用子查询。它将具有以下形式:

select u.user_code_type, sum(problemquantity) as problemquantity,
       min(solvedolderdate) as solvedolderdate,
       min(unsolvedolderdate) as unsolvedolderdate
from (select u.user_code_type, u.user_id,
             . . . <-- rest of your query here
     ) t
group by u.user_code_type