SQL select 图片,带子查询的聚合函数

SQL select image, aggregate functions with subqueries

我正在尝试编写如下所示的查询。 table hnh 包含一组产品的列表,每个产品都有产品图像、范围代码(类型)、项目编号、价格、描述等。SALESORDERHISTORY 是去年各个销售行的列表,其中包含帐户、项目编号、范围代码、销售数量和确认日期。

查询 select 每个 select 客户每条产品线最近 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'

我见过不少例子,但都只有一个子查询、一个聚合函数且没有图像。非常感谢帮助。

我花了很长时间,但答案似乎是在 'from' 之后为图像以外的所有项目创建一个子查询,然后通过主键返回到 select 图像列:

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

如果有人有更好的解决方案请务必更新