繁体   English   中英

SQL:动态日期创建问题

[英]SQL: Dynamic Date creation issue

需要建议以使其动态于日期。

预期:日期,总卖家,上一日期的卖家

当前:表格中的数据(active_seller_codes):日期,seller_code

查询:-明智的日期卖方计数

select date,count(distinct seller_code) as Sellers_COunt  
from active_seller_codes where date between '2016-12-15' AND '2016-12-15'

-前几天的卖家

select date,count(distinct seller_code) as Last_Day_Seller  
from active_seller_codes 
where date between '2016-12-15' AND '2016-12-15'
  and seller_code IN(
    select seller_code from active_seller_codes 
    where date between '2016-12-14' AND '2016-12-14'
  )
group by 1

数据库使用:Vertica

专心阅读,您似乎想要报表中的一行,前两列中包含搜索日期的数据,第三列和第四列中包含搜索日期前一天的数据,如下所示:

sales_date|sellers_count|prev_date |prev_sellers_count
2016-12-15|            8|2016-12-14|                 5

解决方案可能是这样的(没有第一个通用表表达式,在我的情况下,它包含数据,但是在您的情况下,数据将在您的active_seller_codes表中。

WITH
-- initial input
  (sales_date,seller_code) AS (
          SELECT DATE '2016-12-15',42
UNION ALL SELECT DATE '2016-12-15',43
UNION ALL SELECT DATE '2016-12-15',44
UNION ALL SELECT DATE '2016-12-15',45
UNION ALL SELECT DATE '2016-12-15',46
UNION ALL SELECT DATE '2016-12-15',47
UNION ALL SELECT DATE '2016-12-15',48
UNION ALL SELECT DATE '2016-12-15',49
UNION ALL SELECT DATE '2016-12-14',42
UNION ALL SELECT DATE '2016-12-14',44
UNION ALL SELECT DATE '2016-12-14',46
UNION ALL SELECT DATE '2016-12-14',48
UNION ALL SELECT DATE '2016-12-14',50
UNION ALL SELECT DATE '2016-12-13',42
UNION ALL SELECT DATE '2016-12-13',43
UNION ALL SELECT DATE '2016-12-13',44
UNION ALL SELECT DATE '2016-12-13',45
UNION ALL SELECT DATE '2016-12-13',46
UNION ALL SELECT DATE '2016-12-13',47
UNION ALL SELECT DATE '2016-12-13',48
UNION ALL SELECT DATE '2016-12-13',49
)
,
-- search argument this, in the real query, would come just after the WITH keyword
-- as the above would be the source table
search_dt(search_dt) AS (SELECT DATE '2016-12-15')
,
-- the two days we're interested in, de-duped
distinct_two_days AS (
SELECT DISTINCT
  sales_date
, seller_code
FROM active_seller_codes
WHERE sales_date IN (
    SELECT           search_dt     FROM search_dt -- the search date
    UNION ALL SELECT search_dt - 1 FROM search_dt -- the day before
  )
)
,    
-- the two days we want one above the other,
-- with index for the final pivot
vertical AS (
SELECT
  ROW_NUMBER() OVER (ORDER BY sales_date DESC) AS idx
, sales_date
, count(DISTINCT seller_code) AS seller_count
FROM distinct_two_days
GROUP BY 2
)
SELECT
  MAX(CASE idx WHEN 1 THEN sales_date   END) AS sales_date
, SUM(CASE idx WHEN 1 THEN seller_count END) AS sellers_count
, MAX(CASE idx WHEN 2 THEN sales_date   END) AS prev_date
, SUM(CASE idx WHEN 2 THEN seller_count END) AS prev_sellers_count
FROM vertical
;    


sales_date|sellers_count|prev_date |prev_sellers_count
2016-12-15|            8|2016-12-14|                 5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM