我们如何在sql的一列中显示category
和subcategory
。两列都存在于同一表TableA
中。
示例:TableA
--------------------------------------
| category | subcategory | Values |
--------------------------------------
| Bird | parrot | 5 |
| Bird | pigeon | 10 |
| Animal | lion | 2 |
| Animal | Tiger | 5 |
--------------------------------------
输出表:
-------------------
| NEW | Value |
--------------------
| Bird | 15 |
| parrot | 5 |
| Piegon | 10 |
| Animal | 7 |
| lion | 2 |
| Tiger | 5 |
--------------------
在输出中,“新建”是一列,我想要分类和子分类。
样本查询以生成数据:
CREATE TABLE #TEMP
(
catgory nvarchar(200),
sub_category nvarchar(200),
[values] nvarchar(200),
)
INSERT INTO #TEMP VALUES ('Bird','parrot',5)
INSERT INTO #TEMP VALUES ('Bird','pigeon',10)
INSERT INTO #TEMP VALUES ('Animal','lion',2)
INSERT INTO #TEMP VALUES ('Animal','Tiger',5)
其中的逻辑是:
我想要分类和子分类在一起,其中分类应该显示所有子分类值的总和,并且应该与输出表的顺序一致
答案 0 :(得分:0)
尝试一下。
select new, [values] from (select catgory, sub_category as 'new', [values] from temp
union all
select catgory, catgory as 'new', sum([values]) from temp group by catgory) order by catgory
输出:
new values
-------------
parrot 5
pigeon 10
Bird 15
lion 2
lion 2
Tiger 5
Animal 9
答案 1 :(得分:0)
WITH cte AS
(
SELECT category,value FROM yourtable WHERE category IS NOT NULL
UNION ALL
SELECT subcategory, value FROM yourtable WHERE subcategory IS NOT NULL
)
SELECT Company as new, value FROM cte
答案 2 :(得分:0)
select category, sum(values) values from table group by category
union
select subcategory, values from table
答案 3 :(得分:0)
表结构:
ID,名称,parentcategoryId
1,动物,空
2,鱼,1
示例mssql:
Select name, subcats = STUFF((
SELECT ',' + NAME
FROM category as cat1 where cat1.parentcategoryId = cat. parentcategoryId
FOR XML PATH('')
), 1, 1, '') from category as cat where parentcategoryId = null
预览:
名称,子猫
动物,鱼
我是通过手机写的,抱歉编辑不正确
答案 4 :(得分:0)
您可以使用cte
:
with cte as (
select t.*,
dense_rank() over (order by category) as seq,
sum([values]) over (partition by category) as sums
from table t
)
select t.cat as new, (case when cat_name = 'category' then sums else c.[values] end) as Value
from cte c cross apply
( values ('category', category), ('sub_category', sub_category) ) t(cat_name, cat)
order by seq, (case when cat_name = 'category' then 1 else 2 end);
答案 5 :(得分:0)
获取主表的总和后需要UNION ALL:
select
case t.sub_category
when '' then t.category
else sub_category
end new,
t.value
from (
select category, '' sub_category, sum([values]) value from temp group by category
union all
select category, sub_category, [values] value from temp
) t
order by t.category, t.sub_category
请参见demo。
结果:
> new | value
> :----- | ----:
> Animal | 7
> lion | 2
> Tiger | 5
> Bird | 15
> parrot | 5
> pigeon | 10
答案 6 :(得分:0)
执行此操作的简单方法是使用grouping sets
:
select coalesce(subcategory, category) as new, sum(val)
from temp
group by grouping sets ( (category), (subcategory, category))
order by category, subcategory
Here是db <>小提琴。