2017-02-02 61 views
0

需要建議將其設置爲動態日期。SQL:動態創建日期問題

預計: 日期,賣方總數,賣家從以前的日期

目前: 數據表(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的

回答

0

細讀,你似乎想在報告中一行,從檢索日期的前兩列中的數據和當天的搜索日期前在第三的數據,並第四列,就像這樣:

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