按另一个分组的结果排序

时间:2016-07-18 05:20:10

标签: sql sql-server

我需要根据另一个查询的分组对某些结果进行排序。

我有一个包含交易的表,其中一个字段是商店。我想要返回按交易日期排序的所有交易,但在此之内我需要拥有属于最先列出最多交易的商店的交易。

例如:


    Date1, Store A, Amount
    Date1, Store B, Amount
    Date2, Store A, Amount
    Date3, Store A, Amount
    Date3, Store B, Amount
    Date3, Store B, Amount
    Date4, Store B, Amount
    Date5, Store B, Amount

Has to be returned as:

    Date1, Store B, Amount
    Date3, Store B, Amount
    Date3, Store B, Amount
    Date4, Store B, Amount
    Date5, Store B, Amount
    Date1, Store A, Amount
    Date2, Store A, Amount
    Date3, Store A, Amount

因为商店B有更多交易

3 个答案:

答案 0 :(得分:3)

我在子查询中使用了一个窗口函数来获得所需的输出。输出应按商店名称记录计数订购交易日期。

SELECT t.date, t.storeName, t.amount
FROM
(
    SELECT date, storeName, amount,
        COUNT(*) OVER(PARTITION BY storeName ORDER BY date) AS storeCount
    FROM yourTable
) t
ORDER BY t.storeCount DESC, t.date

答案 1 :(得分:1)

使用带窗口函数的count来计算按商店划分的行数

SELECT *, store_count = count(*) over (partition by Store)
FROM   yourtalbe
ORDER BY store_count desc

答案 2 :(得分:1)

根据您提供的详细信息,请检查输出:

--table scripts
    CREATE TABLE Store_Data 
   (datevalue datetime, storeinfo nvarchar(40), Amount numeric(18,2))


    INSERT INTO Store_Data
    SELECT '2016-07-16 10:54:33.020','Store B' , 16000
    UNION ALL
    SELECT '2016-07-18 10:54:33.020','Store A' , 15000
    UNION ALL
    SELECT '2016-07-28 10:54:33.020','Store B' , 10800
    UNION ALL
    SELECT '2016-07-20 10:54:33.020','Store A' , 9000
    UNION ALL
    SELECT '2016-07-23 10:54:33.020','Store B' , 1000
    UNION ALL
    SELECT '2016-07-22 10:54:33.020','Store B' , 7000
    UNION ALL
    SELECT '2016-07-08 10:54:33.020','Store B' , 1000
    UNION ALL
    SELECT '2016-07-12 10:54:33.020','Store A' , 1000
    UNION ALL        
    SELECT '2016-07-15 10:54:33.020','Store A' , 11000
    UNION ALL        
    SELECT '2016-07-18 10:54:33.020','Store B' , 1000
    UNION ALL        
    SELECT '2016-07-02 10:54:33.020','Store A' , 5000
    UNION ALL        
    SELECT '2016-07-24 10:54:33.020','Store B' , 1000
    UNION ALL        
    SELECT '2016-07-08 10:54:33.020','Store A' , 100000
    UNION ALL        
    SELECT '2016-07-23 10:54:33.020','Store B' , 5000
    UNION ALL        
    SELECT '2016-07-18 10:54:33.020','Store B' , 10000

    -

- 最终查询

SELECT a.datevalue,
       a.storeinfo,
       a.Amount 
FROM Store_Data AS a 
INNER JOIN
(
    SELECT storeinfo,
           COUNT(1) AS TotalTrans 
    FROM Store_Data
    GROUP BY storeinfo
) AS b
    ON b.storeinfo = a.storeinfo
ORDER BY b.TotalTrans DESC,
         a.datevalue