SQL操作

时间:2017-09-14 15:56:42

标签: sql

我已经完成了一些SQL查询,并且想知道是否可以比这样更容易地做到这一点? 我有一张像

这样的表格
client_guid | begin_date | installation_id | license_type
---------------------------------------------------------
1           | 2017-07-01 | 1111            | 1

我希望获得有关每个月的信息:我们拥有多少有效许可证(' Total'字段),新的许可证数量以及丢失的客户数量(与上个月相比):

Month | Total | New_licenses | Lost_licenses
--------------------------------------------
1     | 712   |  31          |  25

我使用5个临时表(WITH)编写了这样的代码。有没有办法让它变得更容易?

WITH by_month
AS (SELECT distinct
  l.client_guid as client_guid,
  (EXTRACT(MONTH FROM l.begin_date)) as license_month
FROM license l
WHERE l.installation_id<>9999 and l.license_type=1 and client_guid not in (select guid from reports.test_clients) and (EXTRACT(YEAR FROM l.begin_date))=2017
GROUP BY 1, 2
ORDER BY client_guid),
with_first_month
AS (SELECT
  client_guid,
  license_month,
  FIRST_VALUE(license_month) OVER (PARTITION BY client_guid ORDER BY license_month) AS first_month
FROM by_month),
with_total
AS (SELECT 
    license_month as month_num,
    count(client_guid) as "total"
FROM with_first_month
GROUP BY month_num
ORDER BY month_num),
with_new_guids
AS (SELECT 
    first_month,
    count(distinct client_guid) as "new_guids"
FROM with_first_month
GROUP BY first_month
ORDER BY first_month),
with_total_and_new_guids
AS (SELECT
    t.month_num,
    t.total,
    n.new_guids
FROM with_total t, with_new_guids n
WHERE t.month_num=n.first_month),
with_total_prev
AS (SELECT
    t.month_num,
    tn.total as "total_prev"
FROM with_total t, with_total_and_new_guids tn
WHERE tn.month_num = t.month_num-1)
SELECT
    tn.month_num as "Month",
    tn.total as "Active licenses",
    tn.new_guids as "New licenses",
    tp.total_prev+tn.new_guids-tn.total AS "Lost licenses"
FROM with_total_and_new_guids tn
FULL JOIN with_total_prev tp ON tn.month_num=tp.month_num

感谢您的回答!

0 个答案:

没有答案