TGStat
TGStat
Type to search
Advanced channel search
  • flag English
    Site language
    flag Russian flag English flag Uzbek
  • Sign In
  • Catalog
    Channels and groups catalog Regional compilations Thematic compilations Платные каналы Search for channels
    Add a channel/group
  • Ratings
    Rating of channels Rating of groups Posts rating
    Ratings of brands and people
  • Analytics
  • Search by posts
  • Telegram monitoring
  • Promotion
    Advertising through Yandex Business Advertising in channels through TGStat Agency Advertising on TGStat.ru website
Data Science: SQL и Аналитика данных

3 Oct, 13:46

Open in Telegram Share Report

🔥 SQL-задача с подвохом

Что вернёт этот запрос в PostgreSQL?


CREATE TABLE payments (
id int,
amount int
);

INSERT INTO payments VALUES
(1, 100),
(2, 100),
(3, 200);

SELECT
id,
amount,
SUM(amount) OVER (ORDER BY amount) AS total
FROM payments
ORDER BY id;


Многие ожидают:


1 | 100 | 100
2 | 100 | 200
3 | 200 | 400


Но результат будет другим:


1 | 100 | 200
2 | 100 | 200
3 | 200 | 400


По умолчанию PostgreSQL использует окно RANGE ... CURRENT ROW. Строки с одинаковым amount считаются равными соседями и попадают в окно вместе.

Для построчного накопления нужно указать ROWS:


SUM(amount) OVER (
ORDER BY amount, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)



#SQL #PostgreSQL #Database

🫡 Всё про Data Science

🇷🇺 Читайте нас в MAX

5.4k 0 2
Catalog
Channels and groups catalog Channels compilations Search for channels Add a channel/group
Ratings
Rating of Telegram channels Rating of Telegram groups Posts rating Ratings of brands and people
API
API statistics Search API of posts API Callback
Our channels
@TGStat @TGStat_Chat @telepulse @TGStatAPI
Read
Академия TGStat Telegram Research 2019 Telegram Research 2021 Telegram Research 2023
Contacts
Справочный центр Support Email Jobs
Miscellaneous
Terms and conditions Privacy policy Public offer
Our bots
@TGStat_Bot @SearcheeBot @TGAlertsBot @tg_analytics_bot @TGStatChatBot