CREATE TABLE A (
NAME VARCHAR(5)
,PAY INT
);
INSERT INTO A(NAME, PAY) VALUES
('小明','50')
,('小明','50')
,('小華','100')
,('小美','150')
,('小美','150')
,('小美','150')
;
SELECT NAME, SUM(PAY) PAY
FROM (
SELECT A.*, ROW_NUMBER() OVER (PARTITION BY NAME) SN FROM A) B
WHERE SN <= 2
GROUP BY NAME;
CREATE TABLE #temp (
[name] nvarchar(20)
,pay int
)
INSERT INTO #temp([name],pay) Values('小明',50)
INSERT INTO #temp([name],pay) Values('小明',50)
INSERT INTO #temp([name],pay) Values('小明',100)
INSERT INTO #temp([name],pay) Values('小華',100)
INSERT INTO #temp([name],pay) Values('小美',150)
INSERT INTO #temp([name],pay) Values('小美',150)
INSERT INTO #temp([name],pay) Values('小美',150)
SELECT
[name]
,(
SELECT
SUM(pay)
FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY [name] ASC ) as ID
,pay
FROM #temp AS temp_Test
WHERE temp_Test.[name] =#temp.[name]
)AS Temp
WHERE ID <=2
) AS Pay
FROM #temp
GROUP BY [name]
我用MS SQL寫的,可以參考看看。(以上語法僅參考用)