没有 ID 的 SQL Server 分层排序

问题描述 投票:0回答:1

给定一个未排序的表:

房产0 财产1 净销售额
酒吧 总计$ -200
300
总计$ 总计$ 200
酒吧 支持 -400
总计$ 400
酒吧 兄弟 200
培根 100

我需要根据以下条件对其进行排序:

  1. “$total”值对于每个 property0 类别都优先考虑最高,无论净销售额如何
  2. 整个表格以及每个类别均按 net_sales 降序排序

因此最终表将 $total|total 作为第一行,因为该值具有优先级,因此显示总体总销售额,然后 $total 值将位于每个 property0 类别的顶部,而 net_sales 的值递减,例如这个:

房产0 财产1 净销售额
总计$ 总计$ 200
总计$ 400
300
培根 100
酒吧 总计$ -200
酒吧 兄弟 200
酒吧 支持 -400

理想情况下,代码应该适用于具有 n 个属性(可能不止 2 个)的表。

我正在尝试使用带有自连接的递归 CTE 为每次迭代附加一列,但我对这个概念非常陌生,并且总体上对我的 SQL(在 SSMS 中)仍然是一个业余爱好者:

WITH cte AS
(
SELECT   property0 --Anchor
,property1
,net_sales
FROM MyTable
WHERE property0 = '$total' --Since $total in property0 would be the highest level
UNION ALL
SELECT   t.property0 --Recursive
,t.property1
,t.net_sales
FROM MyTable t
INNER JOIN cte
ON t.property1 = cte.property1 AND t.net_sales = cte.net_sales
)
SELECT * FROM cte
ORDER BY net_sales DESC

但这只是给了我最大递归限制错误,因为返回的表是:

房产0 财产1 净销售额
总计$ 总计$ 200

无限重复。

sql oracle sorting ssms hierarchical
1个回答
0
投票

在甲骨文中:

SELECT COALESCE(Property0, '$total') AS Property0,
       COALESCE(Property1, '$total') AS Property1,
       SUM(net_sales) AS net_sales
FROM   table_name t
WHERE  Property0 != '$total'
AND    Property1 != '$total'
GROUP BY ROLLUP(Property0, Property1)
ORDER BY
       t.Property0 ASC NULLS FIRST,
       t.Property1 ASC NULLS FIRST

在 SQL Server 中,几乎是一样的:

SELECT COALESCE(Property0, '$total') AS Property0,
       COALESCE(Property1, '$total') AS Property1,
       SUM(net_sales) AS net_sales
FROM   table_name t
WHERE  Property0 != '$total'
AND    Property1 != '$total'
GROUP BY ROLLUP(Property0, Property1)
ORDER BY
       t.Property0 ASC,
       t.Property1 ASC

对于样本数据:

CREATE TABLE table_name (
  Property0 VARCHAR(10),
  Property1 VARCHAR(10),
  net_sales INT
);

INSERT INTO table_name (Property0, Property1, net_sales) VALUES
  ('bar',    '$total', -200),
  ('foo',    'sauce',   300),
  ('$total', '$total',  200),
  ('bar',    'sup',    -400),
  ('foo',    '$total',  400),
  ('bar',    'bro',     200),
  ('foo',    'bacon',   100);

两个输出:

财产0 财产1 净销售额
总计$ 总计$ 200
酒吧 总计$ -200
酒吧 兄弟 200
酒吧 支持 -400
总计$ 400
培根 100
300

Oracle 小提琴 SQL Server 小提琴

© www.soinside.com 2019 - 2024. All rights reserved.