2017-02-02 32 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

は注意深く読んで、あなたは、最初の2つの列で検索日からのデータと第三内検索日前日のデータとして、レポート内の1つの行をしたいように見えますそのような4列目、:

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