SQL Server : count pairs from two different columns -
i have query need application i'm building, i'm struggling find best answer.
suppose have table named messages, following columns:
messageid, from, to, text i want count messages between from , to such if table looks this:
id text ------------------ 1 b hi 2 b hello 3 c test so want result
a, b, 2 a, c, 1 appreciate help
similar answer gordon, posted 20 seconds later, 1 important difference. ansi sql requires no derived columns appear in group by clause. first use cte compute least , greatest of to/from pairs, , aggregation query on cte. in case, end grouping on actual, not derived, columns.
with cte ( select case when [from] < [to] [from] else [to] end [from], case when [from] >= [to] [from] else [to] end [to] yourtable ) select [from], [to], count(*) cnt cte group [from], [to] note should avoid using sql keywords such from name columns , tables. query work, absolutely have use column [from], because without brackets sql server confound from keyword.
Comments
Post a Comment