在计数上使用最大功能

时间:2016-03-13 20:32:19

标签: sql oracle

我想返回1个结果,年份(日期时间格式),订单数量最多,我正在尝试在MAX上应用COUNT函数来获取值。我哪里出错?

SELECT TO_CHAR(ODATE, 'YYYY') AS Year
     , MAX(COUNT(*))
FROM ORDERS
GROUP BY TO_CHAR(ODATE, 'YYYY')
ORDER BY TO_CHAR(ODATE, 'YYYY');

1 个答案:

答案 0 :(得分:0)

不确定MAX(COUNT(*))在此上下文中是否有效

而是在ORDER上执行COUNT(*)并使用ROWNUM

SELECT * FROM
(
    SELECT TO_CHAR(ODATE, 'YYYY') AS Year, count(*) AS cnt
    FROM ORDERS
    GROUP BY TO_CHAR(ODATE, 'YYYY')
    ORDER BY cnt DESC
)
WHERE ROWNUM = 1

这将确保您只保留具有最高计数的行: 嵌套查询是因为ROWNUMORDER发生之前由Oracle分配了FETCH FIRST x ROWS

请注意,在 Oracle 12c 及更高版本上,您可以使用指令FETCH。很好描述here。 这允许在没有子查询的情况下执行相同操作,因为ORDER之后应用了SELECT TO_CHAR(ODATE, 'YYYY') AS Year, count(*) AS cnt FROM ORDERS GROUP BY TO_CHAR(ODATE, 'YYYY') ORDER BY cnt DESC FETCH FIRST 1 ROWS ONLY;

@Override
public boolean onQueryTextChange(String newText) {
    Log.d(TAG,newText);
    searchStoreList = storeList;
    final List<StoreList> filteredModelList = filter(searchStoreList, newText);
    //((RVStoreAdapter) mAdapter).animateTo(filteredModelList);
    //The above commented line is the old code. Following is how to reset the adapter!
    mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mAdapter = new RVStoreAdapter(getActivity(),storeList,session.getLat(),session.getLongi());
    mRecyclerView.setAdapter(mAdapter);
    mRecyclerView.scrollToPosition(0);
    return true;
}