【问题标题】:SQL query for incoming and outgoing stocks, first and lastSQL查询传入和传出的股票,第一个和最后一个
【发布时间】:2021-12-22 19:50:54
【问题描述】:

我需要进行查询,显示 2021 年 10 月每种型号的销售和库存(进货和出库)。 关键是要获得进出库存,我需要分别获取每月第一天和最后一天的 vt_stocks_cube_sz.qty 。

现在我只写了股票总和(SUM(vt_stocks_cube_sz.qty) 作为股票),但它不正确。

你能帮我按照上面的规则拆分股票吗,我不明白如何正确编写查询。

%%time
SELECT vt_sales_cube_sz.modc_barc2 model,
        SUM(vt_sales_cube_sz.qnt) sales,
        SUM(vt_stocks_cube_sz.qty) as stocks
FROM vt_sales_cube_sz
LEFT JOIN vt_date_cube2 
    ON vt_sales_cube_sz.id_calendar_int = vt_date_cube2.id_calendar_int
LEFT JOIN vt_stocks_cube_sz ON 
    vt_stocks_cube_sz.parent_modc_barc = vt_sales_cube_sz.modc_barc AND
    vt_stocks_cube_sz.id_stock = vt_sales_cube_sz.id_stock AND 
    vt_stocks_cube_sz.id_calendar_int = vt_sales_cube_sz.id_calendar_int AND
    vt_stocks_cube_sz.vipusk_type = vt_sales_cube_sz.price_type
WHERE vt_date_cube2.wk_year_id = 2021 
        AND vt_date_cube2.wk_MoY_id = 10 
        AND vt_sales_cube_sz.id_stock IN 
            (SELECT id_stock 
            FROM vt_warehouse_cube 
            WHERE channel = \'OffLine\') 
GROUP BY vt_sales_cube_sz.modc_barc2

【问题讨论】:

  • 您能否将一些示例行粘贴到您的问题中,这些行与您编写的查询相对应,包括所有连接,但没有SUM() 表达式和GROUP BY 子句?

标签: sql vertica


【解决方案1】:

如果您正在寻找一种稳健且可通用的方法,我建议您使用analytic functions,例如 FIRST_VALUE、LAST_VALUE 或与 RANK 或 ROW_NUMBER 稍有不同的东西。 下面是一个简单的示例,因此您可以重新运行它并将其调整为您正在使用的特定表/字段。 注意:如果您在同一天/最后一天有多个条目,您可能需要一些决胜局。

 with dummy_table as (
    SELECT 1 as month, 1 as day, 10 as value UNION ALL 
    SELECT 1 as month, 2 as day, 20 as value UNION ALL 
    SELECT 1 as month, 3 as day, 30 as value UNION ALL 
    SELECT 2 as month, 1 as day, 5 as value UNION ALL 
    SELECT 2 as month, 3 as day, 15 as value UNION ALL 
    SELECT 2 as month, 5 as day, 25 as value 
)
SELECT 
    month, 
    day,
    case when day = first_day then 'first' else 'last' end as type,
    value,
FROM (
    SELECT *
        , FIRST_VALUE(day) over (partition by month order by day ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as first_day
        , LAST_VALUE(day) over (partition by month order by day ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as last_day
    FROM dummy_table 
) tmp
WHERE day = first_day OR day=last_day

虚拟表:

Row month day value
1 1 1 10
2 1 2 20
3 1 3 30
4 2 1 5
5 2 3 15
6 2 5 25

结果:

Row month day type value
1 1 1 first 10
2 1 3 last 30
3 2 1 first 5
4 2 5 last 25

【讨论】:

    猜你喜欢
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 2013-02-09
    • 1970-01-01
    • 2012-02-02
    相关资源
    最近更新 更多