2014-02-08 98 views
0

使用MS查詢,下面的代碼工作,它找到的模式「銷售價格」,並將其顯示在Excel 2007MS查詢 - 計算多於1場

(Connection code here has been omitted) 
SELECT TOP 1 "Sales Price" AS "SPrice Mode", COUNT(*) Frequency 
FROM "Sales Table" WHERE ("Date of Sale" BETWEEN ? AND ?) AND (City LIKE ?) 
GROUP BY "Sales Price" 
ORDER BY Frequency DESC 
Enter Start Date  Enter END Date Enter City 

我想模式修改此查詢,以便它也能找到2個其他字段的模式,即「每單位價格」和「每票價格」,它們都與「銷售價格」處於相同的「銷售表」中。另外,我希望用戶只需輸入一次參數。搜索網絡後,我一直無法找到解決方案。我嘗試過使用UNION和JOIN的變體,但無濟於事。任何幫助或指導,將不勝感激。提前致謝。

+0

你是什麼意思的「模式」? –

+0

統計模式,這是最常出現的數字。例如,在列表(1,1,2,2,2,2,3,3,4)中,數字「2」將是頻率爲4的模式。 – GDaniels

回答

0

您可以使用窗口函數獲取多列的模式。在以下查詢中,最裏面的查詢計算每個值的計數。下一個子查詢得到最大計數,最外面的查詢得到最大計數的變量值:

select max(case when cnt_sp = max_cnt_sp then "Sales Price" end) as mod_Sales_Price, 
     max(case when cnt_ppu = max_cnt_ppu then "Price Per Unit" end) as mod_Price_Per_Unit, 
     max(case when cnt_ppsf = max_cnt_ppsf then "Price Per SF" end) as mod_Price_Per_SF  
from (select st.*, 
      max(cnt_sp) over() as max_cnt_sp, 
      max(cnt_ppu) over() as max_cnt_ppu, 
      max(cnt_ppsf) over() as max_cnt_ppsf 
     from (select st.*, 
        count(*) over (partition by "Sales Price") as cnt_sp, 
        count(*) over (partition by "Price Per Unit") as cnt_ppu, 
        count(*) over (partition by "Price Per SF") as cnt_ppsf 
      from "Sales Table" st 
      ) st 
    ) st