美好的一天!
是否有一种简单但有效的SQL语法可以根据主键来汇总表中的数据?
例如,我在数据库SampleDB上有表SampleTable1:
|PermaID |Name_of_Person | Cash |
|111 |Michael | 200 |
|111 |Mikel | 100 |
|222 |Kid | 200 |
|222 |Kidd | 200 |
|222 |Kidd | 200 |
|222 |Kid | 200 |
|333 |Him | 100 |
|333 |Him | 200 |
是否会有基于 PermaID 输出摘要的SQL字符串,而不是名称? :
|PermaID |Name_of_Person | Cash |
|111 |Michael | 300 |
|222 |Kid | 800 |
|333 |Him | 300 |
假设正确的名称是检测到的名字SQL。 ..实际表中实际上有三列以上。
..如果没有,我应该在我的UI中输出然后通过循环数组来总结自己吗?
答案 0 :(得分:1)
这可以为您提供您正在寻找的结果
SELECT PermaID,MIN(Name_of_Person),SUM(Cash)
FROM SampleTable1
GROUP BY PermaID
答案 1 :(得分:1)
如果您需要选择第一个记录名称
;with Cte as( Select PermaID ,Name_of_Person,Cash, C=ROW_NUMBER()
over(partition by PermaID order by PermaID )
From SampleTable1
)
Select Cte.PermaID ,Cte.Name_of_Person,SUM(T.Cash)
from Cte Inner Join SampleTable1 T On T.PermaID =Cte.PermaID
Where C=1
Group By Cte.PermaID ,Cte.Name_of_Person
提示样本here
答案 2 :(得分:0)
declare @t table (PermaID INT,Name varchar(10),Cash INT)
INSERT INTO @t (PermaID,Name,Cash)values (111,'Michael',200)
INSERT INTO @t (PermaID,Name,Cash)values (111,'Michae',200)
INSERT INTO @t (PermaID,Name,Cash)values (222,'Raju',300)
INSERT INTO @t (PermaID,Name,Cash)values (222,'Raj',300)
;WITH CTE AS
(select distinct PermaID,Name,Cash from @t)
select distinct PermaID,MAX(Name),SUM(Cash)
from CTE
GROUP BY PermaID