MySQL window function (last_value) does not work - syntax error

537 views Asked by At

I try to run the query below but a syntax error occurs. I checked many times how to write a last value window function correctly but still there must be a mistake that I cannot see. I tried to add three different kind of frame_clause but none of them solved the syntax error. Please, help me to figure it out.

SQL:

select DATE_FORMAT(Day, "%Y-%m") as Months,
SiteId,
ShopId,
Sum(Clicks) as Montly_Clicks,
Sum(Spending) as Montly_Spending,
last_value(Sum(Clicks)) OVER (
PARTITION BY ShopId
ORDER BY DATE_FORMAT(Day, "%Y-%m") desc
-- range between current row and unbounded following
-- ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
-- RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) as LastMonth_Clicks
from
bi_test3.SourceTable
Where SiteId = 103 
and DATE_FORMAT(Day, "%Y-%m") between '2016-04' and '2018-09'
Group by 
DATE_FORMAT(Day, "%Y-%m"),
ShopId
Order by
DATE_FORMAT(Day, "%Y-%m"),
ShopId

Sample from the table:

Id  Day         ShopId  SiteId  Clicks  Spending
16  2018-10-28  5255294 101     186     0.008420
17  2018-10-28  5251217 101      84     0.024163
18  2018-10-28  5252073 101     979     0.006105
19  2018-10-28  5256205 101     171     0.008790

Error message says the problem is near to Partition by

One more thing which might relate to the problem that in my query last_value and over text is not highlighted with colour. Maybe it's a problem because commands, operators, function etc. are always highlighted with different colours in a query. I use MySQL Workbench 8.0.22

Create table script:

CREATE TABLE `SourceTable` (
  `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Primary key of table',
  `Day` date NOT NULL COMMENT 'Day of item.',
  `ShopId` int(10) unsigned NOT NULL COMMENT 'Shop identifier',
  `SiteId` int(10) unsigned NOT NULL COMMENT 'Site identifier',
  `Clicks` int(10) unsigned NOT NULL COMMENT 'Total paid and free clicks on a given day.',
  `Spending` decimal(14,6) DEFAULT NULL COMMENT 'Total sepnding on a given day.',
  PRIMARY KEY (`Id`),
  KEY `Day` (`Day`),
  KEY `ShopId` (`ShopId`),
  KEY `SiteId` (`SiteId`)
) ENGINE=InnoDB AUTO_INCREMENT=4478684 DEFAULT CHARSET=utf8

server verson: mysql Ver 8.0.22 for Win64 on x86_64 (MySQL Community Server - GPL)

0

There are 0 answers