简体   繁体   中英

SQL window function over partition by syntax error

I have a test table with two columns brand and store

brand store
A a
A b
B a

I'm trying to use the window function to get the output like this

brand store num_stores
A a 2
A b 2
B a 1

Here's what I've been trying on both presto sql and sqlite but keep getting "(" syntax error.

select brand, store, 
count(store) OVER (PARTITION BY brand) as num_stores
from table

Struggling to find why I got this error and how to fix. Appreciate your help:))

It could be that your particular database does not support analytic functions. In that case, you could, as a workaround, try the following:

SELECT t1.brand, t1.store, t2.cnt AS num_stores
FROM yourTable t1
INNER JOIN
(
    SELECT brand, COUNT(store) AS cnt
    FROM yourTable
    GROUP BY brand
) t2
    ON t2.brand = t1.brand;

You can try with the below query:

select brand, store, count(*) OVER (PARTITION BY brand, store) as num_stores from table;

You are missing () brackets for alias covering. You can check my query in db-fiddle

SELECT 
      Brand, 
      Store, 
      (COUNT(Store) OVER (PARTITION BY Brand)) as Num_Stores
FROM your_table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM