以下查询返回我需要的信息;两列是状态号,第二列是总数。
SELECT T.number as 'Number',T.total as 'highest service level'
FROM(
SELECT PARTNER_WORKORDER.statusNo as number, count(statusNo) as total
FROM PARTNER_WORKORDER
inner join PARTNER_WORKORDER_ADDRESS
ON PARTNER_WORKORDER.salesOrderNo = PARTNER_WORKORDER_ADDRESS.salesorder_no
WHERE orderDt <= '2012-11-20 00:00:00.000' AND country_code <> 'US'
group by PARTNER_WORKORDER.statusNo
)
AS T
我现在需要做的是返回最高总数和匹配它的状态号。我知道MAX会给我最高的总数,但我不知道如何获得与该总数相匹配的状态数。我想我需要使用CASE,但我从未有过这方面的经验。
非常感谢任何帮助。
答案 0 :(得分:4)
只需使用order by
和limit
或top
或fetch first 1 row only
即可。例如:
SELECT PARTNER_WORKORDER.statusNo as number, count(statusNo) as total
FROM PARTNER_WORKORDER inner join
PARTNER_WORKORDER_ADDRESS
ON PARTNER_WORKORDER.salesOrderNo = PARTNER_WORKORDER_ADDRESS.salesorder_no
WHERE orderDt <= '2012-11-20 00:00:00.000' AND country_code <> 'US'
group by PARTNER_WORKORDER.statusNo
ORDER BY total desc
LIMIT 1
请注意,您不需要子查询。 SQL标准将是fetch first 1 rows only
而不是limit 1
,但并不是那么多数据库支持(还有)。