我遇到了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)
这里是没有我的代码的第二/底部的输出= GROUP BY,HAVING。
预先感谢
答案 0 :(得分:0)
这有效,请参见下面的结果。 请注意,麦迪逊/天然气的数据仅为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
答案 1 :(得分:0)
通过使用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