Sql server sql:查找多维数据集中的最大数字

Sql server sql:查找多维数据集中的最大数字,sql-server,ssas,cube,olap-cube,Sql Server,Ssas,Cube,Olap Cube,我面临一个SQL OLAP多维数据集问题,无法获得所需的输出。当我执行代码时,我当前得到0行 问题:对于每个城镇,找到数量最多的产品id 下面是我的代码: SELECT [supplier town], [product id], [quantity] FROM my_cube WHERE "supplier town" is not null AND "supplier name" is not null GROUP BY [supplier town], [product id], [qua

我面临一个SQL OLAP多维数据集问题,无法获得所需的输出。当我执行代码时,我当前得到0行

问题:对于每个城镇,找到数量最多的产品id

下面是我的代码:

SELECT [supplier town], [product id], [quantity]
FROM my_cube
WHERE "supplier town" is not null
AND "supplier name" is not null
GROUP BY [supplier town], [product id], [quantity]
HAVING [quantity] >= ALL(
   SELECT [quantity]
   FROM my_cube)
这里是没有代码的第二/底部部分的输出=groupby,have


提前感谢

此功能有效,请参见下面的结果。 请注意,麦迪逊/煤气公司的数据仅为200000, Stevens Point有两个相同数量的产品,并且添加了Wausau

SELECT [supplier town], [product id], [quantity]
FROM my_cube aa
WHERE "supplier town" is not null
--AND "supplier name" is not null
GROUP BY [supplier town], [product id], [quantity]
HAVING [quantity] >= ALL(
   SELECT [quantity]
   FROM my_cube bb where aa.[supplier town] = bb.[supplier town])

supplier town   product id  quantity
Chicago         Computer    1010
Madison         Gas         200000
Springfield     Computer    100
Stevens Point   Airplane    110000
Stevens Point   Computer    110000
Wausau          Boat        200100

通过使用SQL排名函数,可以获得解决此问题的更简洁的方法。例如

drop table if exists #data;

create table #data(
    city nvarchar(100) ,
    product nvarchar(100) ,
    quantity int
);

insert  #data
values  ('Chicago', 'Airplane', 1000) ,
        ('Chicago', 'Boat', 10) ,
        ('Chicago', 'Computer', 1010) ,
        ('Stevens Point', 'Computer', 100) ,
        ('Stevens Point', 'Airplane', 110000) ,
        ('Stevens Point', 'Computer', 110000)
;


select  city ,
        product ,
        quantity ,
        row_number() over (partition by city order by quantity desc, product desc) as [order]
from    #data
如果您只想为每个城市选择排名靠前的一个,那么最终的查询会稍微复杂一些,但也不错

select  *
from    (
    select  city ,
            product ,
            quantity ,
            row_number() over (partition by city order by quantity desc, product desc) as [order]
    from    #data
) x
where   x.[order] = 1
。。。或者,如果你想变得花哨,使用CTE的

with
    x as (
        select  city ,
                product ,
                quantity ,
                row_number() over (partition by city order by quantity desc, product desc) as [order]
        from    #data
    )
select * from x where [order] = 1

对于SQL Server问题,请不要使用
mysql
标记。