DUKESQLMOOC10203中没有更多的假脱机空间

时间:2017-07-24 09:28:17

标签: sql teradata

select deptinfo.dept, deptinfo.deptdesc, skuinfo.brand, skuinfo.style, skuinfo.color, max(total) from
(select deptinfo.dept, deptinfo.deptdesc, skuinfo.brand, skuinfo.style, skuinfo.color, sum(trnsact.amt) as total
from deptinfo
inner join skuinfo
on deptinfo.dept = skuinfo.dept
inner join trnsact
on skuinfo.sku = trnsact.sku
where stype = 'R'
group by 1,2,3,4,5) as a
group by 1,2,3,4,5
order by 6 desc;

我收到此错误:

  

DUKESQLMOOC10203中没有更多的假脱机空间

1 个答案:

答案 0 :(得分:1)

正如其他人所指出的那样,你的查询在写作时没有意义。您正在生成一个中间结果集/子查询,其中包含sum(trnsact.amt)的每个不同组合的deptinfo.dept, deptinfo.deptdesc, skuinfo.brand, skuinfo.style, and skuinfo.color

到目前为止这一切都很好。如果您想获得具有最大sum(trnsact.amt)的部门,您可以使用ORDER BY total订购该子查询的结果,并在该查询的开头只选择一条SELECT TOP 1的记录: / p>

SELECT TOP 1
    deptinfo.dept,
    deptinfo.deptdesc,
    skuinfo.brand,
    skuinfo.style,
    skuinfo.color,
    sum(trnsact.amt) AS total
FROM deptinfo
    INNER JOIN skuinfo ON deptinfo.dept = skuinfo.dept
    INNER JOIN trnsact ON skuinfo.sku = trnsact.sku
WHERE stype = 'R'
GROUP BY 1,2,3,4,5
ORDER BY total DESC;

作为ORDER BY Total DESC的替代方案,您可以使用QUALIFY语句。如果您有多个" TOP"具有相同sum(trnsact.amt)的记录。第一个查询每次都可能返回不同的结果,因为没有办法说"如果有多个部门/品牌/风格/颜色组合具有相同的总和(trnsact.amt),那么选择最高的记录deptinfo.dept号码"。使用Qualify执行此操作将如下所示:

SELECT 
    deptinfo.dept,
    deptinfo.deptdesc,
    skuinfo.brand,
    skuinfo.style,
    skuinfo.color,
    sum(trnsact.amt) AS total
FROM deptinfo
    INNER JOIN skuinfo ON deptinfo.dept = skuinfo.dept
    INNER JOIN trnsact ON skuinfo.sku = trnsact.sku
WHERE stype = 'R'
GROUP BY 1,2,3,4,5
QUALIFY ROW_NUMBER() OVER (ORDER BY total DESC, dept DESC) = 1;

在查询中耗尽假脱机空间的最可能原因是因为第一个SELECT引用了表名,但这些表名只在子查询的上下文中。通过在第一个SELECT中命名表AGAIN,您将导致交叉连接,实际上将deptinfo中的每个记录与skuinfo中的每个记录以及trnsact中的每个记录连接到子查询中的每个记录这将是巨大的,即使你的桌子很小。它也不是你想要的。

当您使用子查询时,您的外部SELECT,WHERE,ORDER BY,GROUP BY和QUALIFY引用您给出子查询的别名,如下所示(使用上面两个查询中的一个查找结果,这只是如何使用子查询的示例:

select a.dept, a.deptdesc, a.brand, a.style, a.color, max(total) from
(select deptinfo.dept, deptinfo.deptdesc, skuinfo.brand, skuinfo.style, skuinfo.color, sum(trnsact.amt) as total
from deptinfo
inner join skuinfo
on deptinfo.dept = skuinfo.dept
inner join trnsact
on skuinfo.sku = trnsact.sku
where stype = 'R'
group by 1,2,3,4,5) as a
group by 1,2,3,4,5
order by 6 desc;

就像我上面提到的那样,这仍然不能为你提供你想要的结果,但至少你现在可以运行它,看看为什么结果不符合你的期望。