我在SQL Server中有下列数据的表:串联值
+-----------------+-------------------+-------------------+--------+
|Product Family | Product Class | Product | Sales |
|Food | Vegetables | Cauliflower | 24 |
|Food | Prepared Meals | Steak & Patatoes | 54 |
|Food | Fruit | Apples | 76 |
|Food | Fruit | Oranges | 14 |
|Food | Fruit | Pears | 32 |
|Electronics | MP3 Players | Cool Player Z | 57 |
|Electronics | MP3 Players | iStuff 16GB | 45 |
|Electronics | TV's | HD | 96 |
|Electronics | TV's | Ultra HD | 76 |
+-----------------+-------------------+-------------------+--------+
有一个在这个数据的层次结构:
- 产品系列
- 产品类
- 产品
我想创建一个将返回每个层次级别的总和的查询。该工会这是否:
SELECT 1 as Level, [Product Family] as Item, SUM(SALES) as Sales
FROM [dbo].[HK_Termp_01] GROUP BY [Product Family]
UNION ALL
SELECT 2 as Level, [Product Class] as Item, SUM(SALES) as Sales
FROM [dbo].[HK_Termp_01] GROUP BY [Product Class]
UNION ALL
SELECT 3 as Level, Product as Item, SUM(SALES) as Sales
FROM [dbo].[HK_Termp_01] GROUP BY Product
不过,我也需要额外的列,这将是3个列的拼接,层次结构中的顺序。期望的输出是:
+--------------------------+-----------------------------------------------+--------+
| Level ||Item | Hierarchy | Sales |
| 1 ||Electronics | Electronics | 274 |
| 1 ||Food | Food | 200 |
| 2 ||Fruit | Food > Fruit | 122 |
| 2 ||MP3 Players | Electronics > MP3 Players | 102 |
| 2 ||Prepared Meals | Food > Prepared Meals | 54 |
| 2 ||TV's | Electronics > TV's | 172 |
| 2 ||Vegetables | Food > Vegetables | 24 |
| 3 ||Apples | Food > Fruit > Apples | 76 |
| 3 ||Cauliflower | Food v Vegetables > Cauliflower | 24 |
| 3 ||Cool Player Z | Electronics > MP3 Players > Cool Player Z | 57 |
| 3 ||HD | Electronics > TV's > HD | 96 |
| 3 ||iStuff 16GB | Electronics v MP3 Players > iStuff 16GB | 45 |
| 3 ||Oranges | Food > Fruit > Oranges | 14 |
| 3 ||Pears | Food > Fruit v Pears | 32 |
| 3 ||Steak & Patatoes | Food v Prepared Meals > Steak & Patatoes | 54 |
| 3 ||Ultra HD | Electronics > TV's > Ultra HD | 76 |
+--------------------------+--------------+------+-------------------------+--------+
这是我卡住的地方。我无法将所有3个字段添加到联盟中的每个查询中,因为那样我就不能按级别获得正确的总数。但我不确定还有什么其他途径可以尝试。
谢谢&让我知道我可以提供什么其他信息来澄清案件。
你可以通过显示你想要得到的结果来澄清问题。 –
完成,谢谢戈登 –