我有一个包含3列的表格:
A B C
test1 10
test1 15
test1 15
test2 1
test2 4
test2 3
test3 3
test3 3
test3 3
在第3栏中,我需要Count of Max(B) Row grouped on A
。输出应该是:
A B C
test1 10 2
test1 15 2
test1 15 2
test2 1 1
test2 4 1
test2 3 1
test3 3 3
test3 3 3
test3 3 3
答案 0 :(得分:0)
这是一个解决方案:
DECLARE @t TABLE ( A VARCHAR(20), B INT, C INT )
INSERT INTO @t
( A, B )
VALUES ( 'test1', 10 ),
( 'test1', 15 ),
( 'test1', 15 ),
( 'test2', 1 ),
( 'test2', 4 ),
( 'test2', 3 ),
( 'test3', 3 ),
( 'test3', 3 ),
( 'test3', 3 )
UPDATE t1
SET C = ca.C
FROM @t t1
CROSS APPLY ( SELECT TOP 1
COUNT(*) AS C
FROM @t t2
WHERE t2.A = t1.A
GROUP BY B
ORDER BY C DESC
) ca
SELECT *
FROM @t
输出:
A B C
test1 10 2
test1 15 2
test1 15 2
test2 1 1
test2 4 1
test2 3 1
test3 3 3
test3 3 3
test3 3 3
答案 1 :(得分:0)
。 你好,
这可能是一个比已经发布的解决方案更好的解决方案,因为它只需要1/3的cpu power / ram,因为它可以批量生成所有内容,而不是间接循环请求。
-- Generate demo table
CREATE TABLE #temp(a nvarchar(20), b int, c int)
INSERT INTO #temp(a, b)
VALUES (N'test1',10),
(N'test1',15),
(N'test1',15),
(N'test2',1),
(N'test2',4),
(N'test2',3),
(N'test3',3),
(N'test3',3),
(N'test3',3)
GO
-- Selecting the Result
SELECT t.a, t.b, mVal.c
FROM #temp as t
INNER JOIN (
SELECT gmax.a, COUNT(gmax.b) as c
FROM (
SELECT t.a, t.b, MAX(b) OVER(PARTITION BY t.a) as maxVal -- Get Maximum Value per group
FROM #temp as t
) as gmax
WHERE gmax.b = gmax.maxVal -- get only the necessary rows
GROUP BY gmax.a
) mVal
ON t.a = mVal.a
-- Updating into #temp
UPDATE t
SET c = mVal.c
FROM #temp t
INNER JOIN (
SELECT gmax.a, COUNT(gmax.b) as c
FROM (
SELECT t.a, t.b, MAX(b) OVER(PARTITION BY t.a) as maxVal
FROM #temp as t
) as gmax
WHERE gmax.b = gmax.maxVal
GROUP BY gmax.a
) mVal
ON t.a = mVal.a
SELECT *
FROM #temp
DROP TABLE #temp
GO
只有Select和更新才对您有用。其余的仅用于演示目的。
祝你好运, 离子
答案 2 :(得分:-1)
我的方法是使用表格select distinct A and the max(B)
中的@A
加入@B group by A
,A. B.
test 1. 15
test 2. 4
test 3. 3
这样会产生以下结果:
set C =( select the count of A from your table where A= @A ) where A= @A
虽然Fitch的数据是数据循环 您可以更新表格
state = fields.Selection(
[('new','New'), ('open','In Progress'), ('closed','Closed')],
"Status",
)
我跳了你的想法。