我的查询存在一些小问题。我正在努力获得一个项目的总和。我知道我可能错过了一些非常简单的东西,但我很快就被抓住了。如果有人可以看看并给我一个关于如何解决这个问题的建议。
select
(select count(distinct(o1.orderno))
from mck_hvs.orderheader o1 with(nolock)
where o1.orderno = od.orderno and o1.refrigerate = 'Y'
) as TotalColdOrders,
(select count(distinct(o2.orderno))
from mck_hvs.orderdetails o2 with(nolock)
where o2.orderno = od.orderno and o2.drugclass
not in ('null', 'Rx')
) as ControlledOrders,
(select count(distinct(o3.orderno))
from mck_hvs.orderheader o3 with(nolock)
where o3.orderno = od.orderno and o3.pucksideinorder = 'Y' and
o3.totesideinorder = 'N' and o3.numitems > 4
) as RobotOrders,
(select count(distinct(o4.orderno))
from mck_hvs.orderheader o4 with(nolock)
where o4.orderno = od.orderno and o4.pucksideinorder = 'Y' and
o4.totesideinorder = 'Y'
) as ComboOrders,
(select count(distinct(o5.rxnum))
from mck_hvs.orderdetails o5 with(nolock)
where o5.refrigerate = 'Y'
) as TotalColdScripts,
(select count(distinct(o6.rxnum))
from mck_hvs.orderdetails o6 with(nolock)
where o6.orderno = od.orderno and o6.drugclass
not in ('null', 'RX')
) as ControlledScripts,
(select sum(o7.numscripts)
from mck_hvs.orderheader o7 with(nolock)
where o7.orderno = od.orderno and o7.pucksideinorder = 'Y' and
o7.totesideinorder = 'N' and o7.numitems > 4
) as RobotScripts,
(select sum(o8.numscripts)
from mck_hvs.orderheader o8 with(nolock)
where o8.orderno = od.orderno and o8.pucksideinorder = 'Y' and
o8.totesideinorder = 'Y'
) as ComboOrderScripts,
count(distinct(od.orderno)) as TotalOrders,
count(distinct(od.rxnum)) as TotalScripts
from
mck_hvs.orderdetails od with( nolock )
答案 0 :(得分:0)
你应该试试这个:
SELECT
od.orderno,
COUNT(DISTINCT
CASE WHEN oh.refrigerate = 'Y' THEN od.orderno END
) AS totalcoldorders,
COUNT(DISTINCT
CASE WHEN od.drugclass NOT IN ('null', 'Rx') THEN od.orderno END
) AS controlledorders,
COUNT(DISTINCT
CASE
WHEN oh.pucksideinorder = 'Y'
AND oh.totesideinorder = 'N' AND oh.numitems > 4
THEN od.orderno
END
) AS robotorders,
COUNT(DISTINCT
CASE
WHEN oh.pucksideinorder = 'Y' AND oh.totesideinorder = 'Y'
THEN oh.orderno
END
) AS comboorders,
COUNT(DISTINCT
CASE WHEN od.refrigerate = 'Y' THEN od.rxnum END
) AS totalcoldscripts,
COUNT(DISTINCT
CASE WHEN od.drugclass NOT IN ('null', 'RX') THEN od.rxnum END
) AS controlledscripts,
SUM(
CASE
WHEN oh.pucksideinorder = 'Y'
AND oh.totesideinorder = 'N' AND oh.numitems > 4
THEN oh.numscripts
END
) AS robotscripts,
SUM(
CASE
WHEN oh.pucksideinorder = 'Y' AND oh.totesideinorder = 'Y'
THEN oh.numscripts
END
) AS comboorderscripts,
(
SELECT COUNT(DISTINCT orderno)
FROM mck_hvs.orderdetails WITH (nolock)
) AS totalorders,
(
SELECT COUNT(DISTINCT rxnum)
FROM mck_hvs.orderdetails WITH (nolock)
) AS totalscripts
FROM mck_hvs.orderdetails od WITH (nolock)
LEFT JOIN mck_hvs.orderheader oh WITH (nolock)
ON oh.orderno = od.orderno
GROUP BY od.orderno
ORDER BY od.orderno;