我想知道如何查询数据库,我可以返回两个总和,第一个是检查总数,然后是每个检查员的总数,即Joe总共进行了4次检查,但仍然显示故障不同层次的。我是sql的新手,所以到目前为止我已经包含了我的脚本,但如果您需要更多信息,请告诉我。
SELECT InspectorCode AS Inspector, InspectionProcedureName AS [Procedure], COUNT(*) AS Total
FROM UnitData_Vehicle
WHERE (DATEDIFF(day, InspectionDateTime, GETDATE()) = 1)
AND InspectionProcedureName LIKE '%Inspection%'
GROUP BY InspectionProcedureName, InspectorCode
我想看看
Inspector Procedure Total InspTotal
joe 1 - Inspection 1 4
joe 2 - Inspection 3
kit 3 - Inspection 14 14
hugh 1 - Inspection 17 32
hugh 6 - Inspection 15
mike 4 - Inspection 18 18
答案 0 :(得分:2)
我不确定sql server但是oracle跟随查询会得到你想要的结果 -
SELECT zz.Inspector as Inspector,
zz.Procedure as Procedure,
zz.total as total,
case
when zz.c_1 =1 then
zz.InspTotal
else
null
end as InspTotal
FROM (SELECT InspectorCode AS Inspector,
InspectionProcedureName AS Procedure,
COUNT(*) AS Total ,
count(*) over(partition by InspectorCode) InspTotal,
row_number() over( partition by InspectorCode order by InspectionProcedureName) c_1
FROM UnitData_Vehicle
WHERE (DATEDIFF(day, InspectionDateTime, GETDATE()) = 1)
AND InspectionProcedureName LIKE '%Inspection%'
GROUP BY InspectionProcedureName, InspectorCode)zz;
请检查where
条件。
我正在检查并仅为最后一个所需的列工作..
如你所知,你没有告诉任何有关条件......
如果您想澄清此查询中的任何内容,请在此处发表评论..
还有一件事 - 我假设你只需要InspTotal列值一次任何InspectorCode代码.. 我是对的吗?
答案 1 :(得分:1)
select InspectorCode as Inspector
, InspectionProcedureName as Procedure
, count(*) as Total
, count(*) over (partition by InspectorCode) as InspTotal
from UnitData_Vehicle as uv1
where (datediff(day, InspectionDateTime, getdate()) = 1)
and InspectionProcedureName like '%Inspection%'
group by
InspectorCode
, Procedure
count(*) over (partition by InspectorCode)
显然尊重where
条款,但确实计入多个组。有意思:))
答案 2 :(得分:0)
以下示例代码适用于我的数据库
SELECT fiscalmonth,item,fiscalyear
,SUM(valuesale)
,
(SELECT SUM(valueSale)
FROM inbalance b
WHERE b.fiscalmonth <= a.fiscalmonth
and a.fiscalyear =b.fiscalyear
and a.item = b.item
) AS RunningTotal
FROM inbalance a
WHERE a.item='1101'
AND a.fiscalyear=2011
GROUP BY fiscalmonth,item,fiscalyear
通过将我的代码“翻译”到您的查询
SELECT InspectorCode AS Inspector, InspectionProcedureName AS [Procedure], COUNT(*) AS Total
, (
SELECT COUNT(*) FROM UnitData_Vehicle b
WHERE a.InspectorCode = b.InspectorCode
AND b.InspectionProcedureName <= b.InspectionProcedureName
GROUP BY InspectionProcedureName,InspectorCode
) As InspTotal
FROM UnitData_Vehicle a
WHERE (DATEDIFF(day, InspectionDateTime, GETDATE()) = 1)
AND InspectionProcedureName LIKE '%Inspection%'
GROUP BY InspectionProcedureName, InspectorCode