2016-02-09 96 views
0

我試圖寫下面的查詢。表格hnh包含每個包含productimage,範圍代碼(類型),項目編號,價格,描述等的設置產品列表。SALESORDERHISTORY是去年單個銷售行的列表,其中包含帳戶,itemnumber,rangecode,salesqty和confirdate列。SQL選擇圖像,具有子查詢的聚合函數

查詢中需要使用匯總函數來爲每個選定客戶的每個產品線選擇最後3個月的銷售額,對於12個月的銷售額也是如此。這可能會改變或平均銷售數量。

select hnh.image, 
    hnh.rangecode, 
    hnh.itemnumber, 
    hnh.producttype, 
    hnh.productdescription, 
    hnh.price, 
    count(distinct a.SalesQty) as '3MonthSales', 
    count(distinct b.SalesQty) as '12MonthSales', 
    hnh.CurrentStock 
    from HNHPRODUCTS hnh 
inner join (select SALESQTY, itemid, configid, account from SALESORDERHISTORY 
    where confirmeddate > DATEADD(month, -3, getdate())) a on a.rangecode = hnh.rangecode and a.itemnumber = hnh.itemnumber and a.account = '1234' 
inner join (select SALESQTY, itemid, configid, account from SALESORDERHISTORY 
    where confirmeddate > DATEADD(month, -12, getdate())) b on b.rangecode = hnh.rangecode and b.itemnumber = hnh.itemnumber and b.account = '1234' 

我見過好幾個例子,但都只有一個子查詢,一個聚合函數和沒有圖像。非常感謝。

回答

1

我花了相當長一段時間,但答案似乎是創建後,「從」比圖像其他所有項目的子查詢,然後通過主鍵加入回選擇image列:

select hnh.image as image, f1, f2, f3, f4, f5, 3MonthSales.... 
from (select 
    hnh.ID as 't_id', 
    hnh.rangecode as 'F1', 
    hnh.itemnumber as 'F2', 
    hnh.producttype as 'F3', 
    hnh.productdescription 'F4', 
    hnh.price as 'F5', 
    count(distinct a.SalesQty) as '3MonthSales', 
    count(distinct b.SalesQty) as '12MonthSales', 
    ... 
    from HNHPRODUCTS hnh 
    group by hnh.ID, 
    hnh.rangecode, 
    hnh.itemnumber, 
    hnh.producttype, 
    hnh.productdescription, 
    hnh.price ... 
join (select SALESQTY, itemid, configid, account from SALESORDERHISTORY 
    where confirmeddate > DATEADD(month, -3, getdate())) a on a.rangecode = hnh.rangecode and a.itemnumber = hnh.itemnumber and a.account = '1234' 
join (select SALESQTY, itemid, configid, account from SALESORDERHISTORY 
    where confirmeddate > DATEADD(month, -12, getdate())) b on b.rangecode = hnh.rangecode and b.itemnumber = hnh.itemnumber and b.account = '1234') as x 
left join x on HNHPRODUCTS.ID = x.t_id 

如果有人有更好的解決方法,請更新