部门十大项目

时间:2017-10-19 19:36:38

标签: sql ms-access

我在调整此查询时遇到问题,以获取部门的十大销售风格。我已经在网上看到了关于如何使用子查询执行此操作的各种示例,但它们都没有包含条件或连接,因此我有点迷失。

我目前的查询如下。任何帮助将不胜感激!

SELECT
    T1.DEPT,
    T1.SKU,
    T1.COLOR,
    SUM(T1.SALES) AS Sales,
    SUM(T1.GP) AS GP
FROM Table1 T1
    INNER JOIN Table2 T2 ON T1.Date = T2.Date
WHERE
    T2.Year = '2017'
    AND T2.Month in ("July, August")
GROUP BY
    T1.DEPT, 
    T1.SKU, 
    T1.COLOR
ORDER BY 4

3 个答案:

答案 0 :(得分:0)

SELECT TOP 10 T1.DEPT, T1.SKU, T1.COLOR FROM T1 IN (
SELECT
    T1.DEPT,
    T1.SKU,
    T1.COLOR,
    SUM(T1.SALES) AS Sales,
    SUM(T1.GP) AS GP
FROM Table1 T1
    INNER JOIN Table2 T2 ON T1.Date = T2.Date
WHERE
    T2.Year = '2017'
    AND T2.Month in ("July, August")
GROUP BY
    T1.DEPT, 
    T1.SKU, 
    T1.COLOR
ORDER BY 4)

答案 1 :(得分:0)

只需将聚合查询保存为存储的Access查询,然后在引用聚合的新查询中运行相关计数子查询:

SELECT DEPT, SKU, COLOR, Sales, GP,
      (SELECT Count(*) FROM QueryAgg sub
       WHERE sub.Sales >= QueryAgg.Sales
         AND sub.DEPT = QueryAgg.DEPT) As [Rank]
FROM QueryAgg
WHERE (SELECT Count(*) FROM QueryAgg sub
       WHERE sub.Sales >= QueryAgg.Sales
         AND sub.DEPT = QueryAgg.DEPT) <= 10
ORDER BY DEPT, Sales DESC

答案 2 :(得分:0)

select T.dept,
       T.sku,
       T.color,
       T.Sales as sumsales,
       T.GP as sumgp
       row_number() over(partition by T.dept order by T.Sales desc) as rownum
from (SELECT T1.DEPT, T1.SKU, T1.COLOR,
             SUM(T1.SALES) AS Sales,
             SUM(T1.GP) AS GP
        FROM Table1 T1
        INNER JOIN Table2 T2 ON T1.Date = T2.Date
         WHERE T2.Year = '2017'
          AND T2.Month in ("July, August")
      GROUP BY T1.DEPT, T1.SKU, T1.COLOR) T
where T.rownum <= 10

在From Clause中查询。然后根据部门拆分,按销售总额排序。然后检索每个部门的前十大销售额

您可以替换此

FROM Table1 T1
        INNER JOIN Table2 T2 ON T1.Date = T2.Date
         WHERE T2.Year = '2017'
          AND T2.Month in ("July, August")

AS

FROM TABLE T1
WHERE T1.Year = '2017'
  AND T1.Month in ("July", "August")

我没有看到T2在任何地方使用过,我不需要自我加入。可以使用where子句

来处理它