简体   繁体   English

Group BY的复杂SQL查询

[英]Complex SQL Query of Group BY

I have 4 Tables ( Cattle , Farm , Vaccine , vReminder ) I want to select from Vaccine Reminder table all reminders to be shown as 我有4个表格(牛,农场,疫苗,vReminder),我想从疫苗提醒表中选择所有要显示的提醒

( 2 ( Cows ) have ( Vaccine Name 1) from ( Farm Name 1) on this Date ) ( 3 ( Horses) have ( Vaccine Name 1) from ( Farm Name 1) on this Date ) ( 1 ( Cow) have ( Vaccine Name 5) from ( Farm Name 2) on this Date ) and so On (2(母牛)在这个日期有(农场名称1)的(疫苗名称1))(3(马)在这个日期有(农场名称1)的(疫苗名称1))(1(母牛)有(疫苗)名称(5)的日期(农场名称2)的日期,依此类推

I wrote this Query But it is not Grouping the same Vaccine Type that are located for the same Farm if the cattle is of the same type : 我编写了此查询,但是如果牛的类型相同,则不会为同一农场分配相同的疫苗类型: 在此处输入图片说明

My Query : 我的查询:

  SELECT 
  (Select v.vName from vaccine as v where v.vID= vr.[vID]),
  vr.[Type],
  vsD,
  COUNT(vr.[Type]),
  f.farmName
  FROM [QNFARM].[dbo].[vReminder] as vr  inner join
       [cattle] as c on c.RFID = vr.RFID inner join
       farm as f on f.farmID = c.fID    
  Group by
  vr.vID,
  vr.Type,
  vsD,
  vr.RFID,
  f.farmName

But as you See in the screen shot that it is Vname Pinkeye for to same breeds and same Dates and same Farm it does not Group Them . 但是,正如您在屏幕快照中看到的那样,对于相同的品种,相同的日期和相同的农场,它是Vname Pinkeye,它没有对它们进行分组。

The Problem that I was grouping also by RFID of the cattle that was preventing the group function to collect the Same vaccine id , so the correct query is : 我也正在通过牛的RFID分组的问题阻止了分组收集相同疫苗ID的功能,所以正确的查询是:

  SELECT f.farmName,vr.[Type],
  (Select v.vName from vaccine as v where v.vID= vr.[vID]) as vName,vr.vsD
  ,COUNT(*) as Num
  FROM [QNFARM].[dbo].[vReminder] as vr inner join  [cattle] as c on c.RFID=vr.RFID  inner join farm as f on f.farmID=c.fID    Group by f.farmName,vr.Type,vr.vID,vr.vsD

I just remove the RFID from the group by statement and the result now 我只是从声明中删除RFID,现在将结果 在此处输入图片说明

Don't use a subquery to get the vaccine name. 不要使用子查询来获取疫苗名称。 Just use joins: 只需使用联接:

SELECT v.vName, vr.[Type], vsD, COUNT(*), f.farmName
FROM [QNFARM].[dbo].[vReminder] vr INNER JOIN
     [cattle] c 
     ON c.RFID = vr.RFID  INNER JOIN 
     farm f 
     ON f.farmID = c.fID INNER JOIN
     vaccine v
     ON v.vid = vr.vid
GROUP BY v.vname, vr.Type, vsD, f.farmName;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM