新的和学习的,需要帮助清理它

时间:2016-06-24 16:01:48

标签: sql reporting-services

我是SQL的新手,并且已经从这个论坛上阅读和学习了很多东西。我写了下面的查询,看起来很接近,有人可以帮忙吗?

Inc_main occup_id类型已完成staff_id 000001 200 2009年1月22日MCGI01 000001 200 27-Feb-09 MCGI01 000003 200 30-Dec-08 CRIT01

Occ_main occup_id名称insp_dist区号街道st_type 000003商业名称62 1 10945街道名称RD 000004商业名称61 2 9730街道名称RD 000005商业名称62 1 10965街道名称RD

SELECT 
  occ_main.insp_dist, Ins_main.Occup_id, Ins_main.Completed, Ins_main.Type, Ins_main.staff_id,DATEDIFF  (Day,Ins_main.completed,GETDATE())AS diffdate
FROM
  Occ_main INNER JOIN Ins_main.occup_id ON Occ_main.occup_id = Ins_main.occup_id INNER JOIN
  Ins_main INNER JOIN(SELECT ins_main.Occup_id, MAX(ins_main.Completed) as maxdate
    FROM Ins_main
    group by ins_main.Occup_id) c2
    ON c2.Occup_id = Ins_main.Occup_id
    and c2.maxdate = Ins_main.Completed


GROUP BY
  occ_main.insp_dist,
  Ins_main.occup_id,
  Ins_main.completed,
  Ins_main.type,
  Ins_main.staff_id

1 个答案:

答案 0 :(得分:1)

你的加入有点搞砸了。试试这个:

SELECT 
  occ_main.insp_dist, Ins_main.Occup_id, Ins_main.Completed, Ins_main.Type, Ins_main.staff_id, 
  DATEDIFF(Day,Ins_main.completed, GETDATE()) AS diffdate
FROM
  Occ_main INNER JOIN Ins_main 
  ON Occ_main.occup_id = Ins_main.occup_id 
  INNER JOIN (SELECT ins_main.Occup_id, MAX(ins_main.Completed) as maxdate
    FROM Ins_main
    group by ins_main.Occup_id) c2
    ON c2.Occup_id = Ins_main.Occup_id
    and c2.maxdate = Ins_main.Completed 
GROUP BY
  occ_main.insp_dist,
  Ins_main.occup_id,
  Ins_main.completed,
  Ins_main.type,
  Ins_main.staff_id