L
L
Loonerd22021-05-24 11:08:33
SQLite
Loonerd2, 2021-05-24 11:08:33

How to combine multiple requests into one?

There is a database with positions of search requests. Now we have to write a separate request for each of the cities and get the necessary data. Request example:

SELECT Query AS "Ключевая фраза",
   SUM(CASE Updated WHEN '2021-05-20'  THEN Yandex ELSE 0 END) AS "Я 2021-05-20 Екб"
 
FROM Queries c LEFT JOIN
   SitePositions o ON c.Id = o.QueryId
   WHERE SiteId = 33 AND RegionCode = 54
GROUP BY QueryId


The essence is in RegionCode. For example, for Yekaterinburg it can be 54. Relatively speaking, for Voronezh - 193. What is the result:
60ab5db442319414148766.png

For Voronezh, the following query is used:
SELECT Query AS "Ключевая фраза",
   SUM(CASE Updated WHEN '2021-05-20'  THEN Yandex ELSE 0 END) AS "Я 2021-05-20 Воронеж"
 
FROM Queries c LEFT JOIN
   SitePositions o ON c.Id = o.QueryId
   WHERE SiteId = 33 AND RegionCode = 193
GROUP BY QueryId


How should I complete the query to combine these two queries into 1? The expected result is something like this:
60ab5eff0c709141917838.png

The structure of the Queries and SitePosition tables is as follows, respectively:
60ab5f6e5c044734516839.png
60ab5f82885bd111990339.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-05-24
@Loonerd2

SELECT 
  Query AS "Ключевая фраза",
  SUM(CASE WHEN (Updated = '2021-05-20' AND RegionCode = 54) THEN Yandex ELSE 0 END) AS "Yandex ekb",
  SUM(CASE WHEN (Updated = '2021-05-20' AND RegionCode = 193) THEN Yandex ELSE 0 END) AS "Yandex vor"
FROM Queries c 
LEFT JOIN SitePositions o ON c.Id = o.QueryId
WHERE SiteId = 33
GROUP BY QueryId, Query;

SQLite fiddle

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question