将 Impala SQL 的多个值合并为 1
Combine multiple value into 1 for Impala SQL
我想将多个产品条目合并为 1 个,并将它们的价格相加。目前,数据库看起来像这样:
Name Product Price
Zack Vanilla Twist 1
Jane Lolipop 0.5
Zack Lolipop 0.5
Zack Candymint 0.5
Jane ChocoLoco LM 1.5
我想把它的外观改成这样:
Name Product sum(Price)
Zack Vanilla Twist, Lolipop, Candymint 2
Jane Lolipop, ChocoLoco LM 2
如何使用 Impala SQL?
declare @temp table (Name varchar(50), product varchar(50), Price decimal(3,1))
insert into @temp values ('Zack','Vanilla Twist',1)
insert into @temp values ('Jane','Lolipop',0.5)
insert into @temp values ('Zack','Lolipop',0.5)
insert into @temp values ('Zack','Candymint',0.5)
insert into @temp values ('Jane','ChocoLoco LM',1.5)
-- No cursor, Whil loop, or User defined function:
SELECT
Name,
STUFF((
SELECT ', ' + product
FROM @temp
WHERE (name = Results.name)
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
,1,2,'') AS Product
,sum(Price) as [Sum(Price)]
FROM @temp Results
GROUP BY name
输出:
Name Product Sum(Price)
Jane Lolipop, ChocoLoco LM 2
Zack Vanilla Twist, Lolipop, Candymint 2
此查询适用于 MySQL,这可能对您有所帮助。
select Name, group_concat(`product` separator ', ') Product, sum(Price)
from tempt
group by Name
order by Name desc
我想将多个产品条目合并为 1 个,并将它们的价格相加。目前,数据库看起来像这样:
Name Product Price
Zack Vanilla Twist 1
Jane Lolipop 0.5
Zack Lolipop 0.5
Zack Candymint 0.5
Jane ChocoLoco LM 1.5
我想把它的外观改成这样:
Name Product sum(Price)
Zack Vanilla Twist, Lolipop, Candymint 2
Jane Lolipop, ChocoLoco LM 2
如何使用 Impala SQL?
declare @temp table (Name varchar(50), product varchar(50), Price decimal(3,1))
insert into @temp values ('Zack','Vanilla Twist',1)
insert into @temp values ('Jane','Lolipop',0.5)
insert into @temp values ('Zack','Lolipop',0.5)
insert into @temp values ('Zack','Candymint',0.5)
insert into @temp values ('Jane','ChocoLoco LM',1.5)
-- No cursor, Whil loop, or User defined function:
SELECT
Name,
STUFF((
SELECT ', ' + product
FROM @temp
WHERE (name = Results.name)
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
,1,2,'') AS Product
,sum(Price) as [Sum(Price)]
FROM @temp Results
GROUP BY name
输出:
Name Product Sum(Price)
Jane Lolipop, ChocoLoco LM 2
Zack Vanilla Twist, Lolipop, Candymint 2
此查询适用于 MySQL,这可能对您有所帮助。
select Name, group_concat(`product` separator ', ') Product, sum(Price)
from tempt
group by Name
order by Name desc