CREATE TABLE t (
id int,
col1 varchar(20),
col2 varchar(20),
col3 varchar(20)
)
GO
INSERT INTO t
SELECT 1, 'x1', 'y2', 'z1'
UNION
SELECT 1, 'x1', 'y1', 'z1'
UNION
SELECT 1, 'x2', 'y2', 'z2'
UNION
SELECT 2, 'x1', 'y1', 'z1'
UNION
SELECT 3, 'x1', 'y1', 'z1'
UNION
SELECT 4, 'x2', 'y2', 'z2'
UNION
SELECT 4, 'x1', 'y1', 'z1'
UNION
SELECT 1, 'x2', 'y1', 'z2'
GO
SELECT
(
SELECT COUNT(*) AS idx
FROM t t2
WHERE t2.id = t1.id AND (
t2.col1 < t1.col1 OR (
t2.col1 = t1.col1 AND (
t2.col2 < t1.col2 OR (
t2.col2 = t1.col2 AND t2.col3 <= t1.col3
)
)
)
)
) AS idx,
id,
col1,
col2,
col3
FROM t t1
DROP TABLE t
GO
id int,
col1 varchar(20),
col2 varchar(20),
col3 varchar(20)
)
GO
INSERT INTO t
SELECT 1, 'x1', 'y2', 'z1'
UNION
SELECT 1, 'x1', 'y1', 'z1'
UNION
SELECT 1, 'x2', 'y2', 'z2'
UNION
SELECT 2, 'x1', 'y1', 'z1'
UNION
SELECT 3, 'x1', 'y1', 'z1'
UNION
SELECT 4, 'x2', 'y2', 'z2'
UNION
SELECT 4, 'x1', 'y1', 'z1'
UNION
SELECT 1, 'x2', 'y1', 'z2'
GO
SELECT
(
SELECT COUNT(*) AS idx
FROM t t2
WHERE t2.id = t1.id AND (
t2.col1 < t1.col1 OR (
t2.col1 = t1.col1 AND (
t2.col2 < t1.col2 OR (
t2.col2 = t1.col2 AND t2.col3 <= t1.col3
)
)
)
)
) AS idx,
id,
col1,
col2,
col3
FROM t t1
DROP TABLE t
GO