select
min(MH.sno) as hatchid,(SH.name+'-'+SH1.name) as hatcheryname
,convert(varchar,SD.settingdate,103)as settingdate
,sum(SD.Recievedeggs) as eggsdispatchqty,sum(SD.quantity) as settingqty
,convert(varchar,MH.pulloutdate,103) as Pulloutdate,SD.batchno as flockno
,sum(MH.ChicksQnty) as Noofchicks,sum(MH.culls) as culls
,cast((round((((MH.ChicksQnty - MH.culls)/SD.quantity)*100),2)) as float) as hatchpercent
,sum(cast(round(((SD.quantity*87)/100),0)as int)) as ActSalablechicks
,sum((MH.Chicksqnty- MH.culls))as Salablechicks
from
K_HM_SetterGetterAllocationDet SD
inner join K_HM_SetterDetails MS on SD.sno=MS.ID
inner join K_HM_HatcherDetails HD on MS.sno=HD.ID
inner join K_HM_MasterHatcherdet MH on HD.Sno=MH.ID
inner join K_HM_GetterSetterDet SH on SD.name=SH.sno
inner join K_HM_GetterSetterDet SH1 on SH1.sno=HD.hatchername
where
HD.attrited='true'
and MH.pulloutdate is not null
and MS.pulloutdate is not null
group by
MH.sno,SH.name,SH1.name,SD.settingdate,MH.pulloutdate,SD.batchno,
MH.Chicksqnty,MH.culls,SD.quantity
order by settingdate desc
我有四个不同的表数据,这四个表有一对一的关系。实际上我想要的是依赖于settingdate列,列的一些总和(列)。我试过这样但是它显示的是不显示行总和的不同行。我怎么写请帮助我。提前致谢
答案 0 :(得分:1)
这是一种格式化的评论。从这个查询开始:
select min(MH.sno) as hatchid
,(SH.name+'-'+SH1.name) as hatcheryname
from K_HM_SetterGetterAllocationDet SD
inner join K_HM_SetterDetails MS on SD.sno=MS.ID
inner join K_HM_HatcherDetails HD on MS.sno=HD.ID
inner join K_HM_MasterHatcherdet MH on HD.Sno=MH.ID
inner join K_HM_GetterSetterDet SH on SD.name=SH.sno
inner join K_HM_GetterSetterDet SH1 on SH1.sno=HD.hatchername
where HD.attrited='true'
and MH.pulloutdate is not null
and MS.pulloutdate is not null
group by SH.name
,SH1.name
如果未成功运行,请对其进行编辑,直到成功为止。然后添加其他聚合并再次运行它。到现在为止应该没问题。
接下来,将其他字段逐个添加到select和group by子句中。每次运行查询以确保它没问题。在出现错误时处理错误。最终,您将获得一个有效的查询。
答案 1 :(得分:1)
如果您使用GROUP BY
中的列,则通常不会在MIN, SUM, etc.
的同一列上使用聚合函数(SELECT
)。
单独查看K_HM_MasterHatcherDet
表,我们可以看到以下查询(基于原始查询):
SELECT MIN(MH.sno) AS hatchid,
CONVERT(varchar, MH.pulloutdate, 103) as Pulloutdate,
SUM(MH.ChicksQnty) as Noofchicks,
SUM(MH.culls) as culls,
SUM(MH.Chicksqnty - MH.culls) as Salablechicks
FROM K_HM_MasterHatcherdet AS MH
WHERE MH.pulloutdate IS NOT NULL
GROUP BY MH.sno, MH.pulloutdate, MH.Chicksqnty, MH.culls
此处的问题是,GROUP BY
会返回每个不同的MH.sno, MH.PulloutDate, MH.Hicksqnty, MH.Culls
,因此MIN(MH.sno)
之类的内容无法实现任何目标。
最好的方法是首先获得所有记录,如下所示:
SELECT MH.sno AS hatchid,
CONVERT(varchar, MH.pulloutdate, 103) as Pulloutdate,
MH.ChicksQnty as Noofchicks,
MH.culls as culls,
(MH.Chicksqnty - MH.culls) as Salablechicks
FROM K_HM_MasterHatcherdet AS MH
WHERE MH.pulloutdate IS NOT NULL
然后从那时起构建GROUP BY
和聚合函数。
下面我得到每个HatchId和PulloutDate的总数:
SELECT MH.sno AS hatchid,
CONVERT(varchar, MH.pulloutdate, 103) as Pulloutdate,
SUM(MH.ChicksQnty) as Noofchicks,
SUM(MH.culls) as culls,
SUM(MH.Chicksqnty - MH.culls) as Salablechicks
FROM K_HM_MasterHatcherdet AS MH
WHERE MH.pulloutdate IS NOT NULL
GROUP BY MH.sno, MH.PulloutDate
这里的主要内容是GROUP BY
句柄MH.sno
和MH.PulloutDate
,而聚合函数则对查询中的其余列进行操作。