具有聚合功能的复杂SQL查询

时间:2019-01-21 20:16:53

标签: sql

我有3张桌子

销售日记销售: DATE-发售日期 T_CODE-产品代码 全-售出数量

Sales journal

产品期刊产品: CODE-产品代码 NAME-产品名称 Products journal

价格日志价格: T_CODE-产品代码 日期-价格更改的日期(即更改后的价格从该日期开始有效,直到下一次价格更改为止) 费用-产品价格 Prices journal

我需要总结2018年前三个月的总销售量和总销售量 Summary

我试图为此构造SQL查询,如下所示:

SELECT PRODUCTS.NAME, PRODUCT.T_CODE

(SELECT SUM(SALES.QUAN) WHERE SALES.DATE BETWEEN '01.01.2018' AND '31.01.2018') AS JANUARY_QUANTITY

(SELECT SUM(SALES.QUAN)*PRICES.COST FROM SALES INNER JOIN PRICES ON PRICES.T_CODE = SALES.T_CODE) AS JANUARY_VALUE

(SELECT SUM(SALES.QUAN) WHERE SALES.DATE BETWEEN '01.02.2018' AND '28.02.2018') AS FEBRUARY_QUANTITY

(SELECT SUM(SALES.QUAN)*PRICES.COST FROM SALES INNER JOIN PRICES ON PRICES.T_CODE = SALES.T_CODE) AS FEBRUARY_VALUE

(SELECT SUM(SALES.QUAN) WHERE SALES.DATE BETWEEN '01.03.2018' AND '31.03.2018') AS MARCH_QUANTITY

(SELECT SUM(SALES.QUAN)*PRICES.COST FROM SALES INNER JOIN PRICES ON PRICES.T_CODE = SALES.T_CODE) AS MARCH_VALUE

LEFT JOIN PRODUCTS.CODE
GROUP BY ST.NAME;

请帮助我为此构建正确的SQL查询。

Sales Products

Prices

Summary - this is what I want to get as the result of the query

1 个答案:

答案 0 :(得分:1)

  

从价格的销售内联价格中选择SUM(SALES.QUAN)*PRICES.COST。T_CODE= SALES.T_CODE)为JANUARY_VALUE

您没有得到缺少与销售日期和价格日期相匹配的JOIN条件的输出。另外,您需要将乘法移到聚合函数中。

将价格放入聚合函数中可以使计算正确进行。

此外,我相信可以使用条件聚合来简化您的查询,如下所示:

SELECT
    SUM(CASE WHEN S.DATE BETWEEN '01.01.2018' AND '31.01.2018' THEN S.QUAN ELSE 0 END) AS JANUARY_QUANTITY,
    SUM(CASE WHEN S.DATE BETWEEN '01.01.2018' AND '31.01.2018' THEN S.QUAN * P.COST ELSE 0 END) AS JANUARY_VALUE,
    SUM(CASE WHEN S.DATE BETWEEN '01.02.2018' AND '28.02.2018' THEN S.QUAN ELSE 0 END) AS FEBRUARY_QUANTITY,
    SUM(CASE WHEN S.DATE BETWEEN '01.02.2018' AND '28.02.2018' THEN S.QUAN * P.COST ELSE 0 END) AS FEBRUARY_VALUE,
    SUM(CASE WHEN S.DATE BETWEEN '01.03.2018' AND '31.03.2018' THEN S.QUAN ELSE 0 END) AS MARCH_QUANTITY,
    SUM(CASE WHEN S.DATE BETWEEN '01.03.2018' AND '31.03.2018' THEN S.QUAN * P.COST ELSE 0 END) AS MARCH_VALUE
FROM 
    SALES S
    LEFT JOIN PRICES P ON P.T_CODE = S.T_CODE AND P.DATE = S.DATE

使用此技术,表格仅扫描一次,然后分析结果以将其输入结果集中的相关列。这应该可以有效地替换您的6个子查询。