Ответы пользователя по тегу MySQL
  • Как вывести список клиентов с непрерывной историей за год?

    @Cairn
    Нельзя группировать просто по номеру месяца в данной ситуации, т.к. у месяцев в разных годах совпадёт номер и они сгруппируются, хотя по идее не должны.
    SELECT ID_client, Avg_check, Total_sum, Purchases, ROUND(Total_sum/Purchases,2) AS Avg_transaction
    FROM (
      WITH per_check_t AS (
        SELECT 
          FIRST(CONCAT(YEAR(date_new),"-",MONTH(date_new))) AS Month, 
          FIRST(CAST(date_new AS DATE)) AS Date, 
          Id_check, 
          FIRST(ID_client) AS ID_client, 
          ROUND(SUM(Sum_payment),2) AS Check_sum,
          COUNT(*) AS n_transactions
        FROM transactions
        GROUP BY Id_check)
      SELECT 
        ID_client, 
        COUNT(DISTINCT Month) AS Months,
        ROUND(AVG(Check_sum),2) AS Avg_check,
        ROUND(SUM(Check_sum),2) AS Total_sum,
        SUM(n_transactions) AS Purchases
      FROM per_check_t
      GROUP BY per_check_t.ID_client
      HAVING Months = 13
      ORDER BY Total_sum DESC) AS full_months
    Ответ написан
    Комментировать