2016-07-18 4 views
0

別のクエリのグループ化に基づいていくつかの結果をソートする必要があります。別のグループ化の結果としてソート

私は取引があるテーブルを持っており、そのフィールドの1つがストアです。私は、取引日によって注文されたすべての取引を返却したいが、その中で最も多くの取引が最初に記載された店舗に属する取引を持つ必要がある。例えば

 

    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は、私は内部の窓関数を使用

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

答えて

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 

    - 

--finalクエリ

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 
1

使用回数より多くのトランザクションを持っているのであなたの望む出力を得るための副問い合わせ。出力は、店舗名レコード数の両方で注文する必要があります。あなたの特定の詳細を1として

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 
3

ストアで行数をカウントするウィンドウ関数と

関連する問題