分组在from和toloc上完成,一组由usrid指示
Table :
from toloc usrid
a b 1
c d 1 --- group 1
e f 1
-------------------
a b 2
c d 2 --- group 2
e f 2
----------------------
a b 3
c d 3 --- group 3
h k 3
组集查询后需要结果???
from toloc usrid
a b 1
c d 1 --- group 1 & 3 combined to form 1 group
e f 1
-------------------
a b 2![alt text][1]
c d 2 --- group 2
h k 2
我怎样才能实现结果集.
我必须在sql中对类似的记录集进行分组.是否可以使用汇总或新的分组集.我无法理解它.
最佳答案 我挖出了这个老问题.假设没有重复的行,它应该工作.
我解决了你首先链接到的那个并重写了它以匹配这个,所以字段与你的例子相比名称不同.
DECLARE @t TABLE (fromloc VARCHAR(30), toloc VARCHAR(30), usr_history INT)
INSERT @t VALUES ('a', 'b', 1)
INSERT @t VALUES ('c', 'b', 1)
INSERT @t VALUES ('e', 'f', 1)
INSERT @t VALUES ('a', 'b', 2)
INSERT @t VALUES ('c', 'b', 2)
INSERT @t VALUES ('e', 'f', 2)
INSERT @t VALUES ('a', 'b', 3)
INSERT @t VALUES ('c', 'd', 3)
INSERT @t VALUES ('h', 'k', 3)
;WITH c as
(
SELECT t1.usr_history h1, t2.usr_history h2, COUNT(*) COUNT
FROM @t t1
JOIN @t t2 ON t1.fromloc = t2.fromloc and t1.toloc = t2.toloc and t1.usr_history < t2.usr_history
GROUP BY t1.usr_history, t2.usr_history
),
d as (
SELECT usr_history h, COUNT(*) COUNT FROM @t GROUP BY usr_history
),
e as (
SELECT d.h FROM d JOIN c ON c.COUNT = d.COUNT and c.h2 = d.h
JOIN d d2 ON d2.COUNT=c.COUNT and d2.h= c.h1
)
SELECT fromloc, toloc, DENSE_RANK() OVER (ORDER BY usr_history) AS 'usrid'
FROM @t t
WHERE NOT EXISTS (SELECT 1 FROM e WHERE e.h = t.usr_history)