1 Assume id + col1 + col2 + col3 is key ,
2 tested in SQL Server 2005.
<pre>
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'
GO
SELECT
(
SELECT COUNT(*) AS idx
FROM t t2
WHERE t2.id = t1.id
AND t2.col1 <= t1.col1
AND t2.col2 <= t1.col2
AND t2.col3 <= t1.col3
) AS idx,
id,
col1,
col2,
col3
FROM t t1
GO
DROP TABLE t
GO
</pre>
2 tested in SQL Server 2005.
<pre>
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'
GO
SELECT
(
SELECT COUNT(*) AS idx
FROM t t2
WHERE t2.id = t1.id
AND t2.col1 <= t1.col1
AND t2.col2 <= t1.col2
AND t2.col3 <= t1.col3
) AS idx,
id,
col1,
col2,
col3
FROM t t1
GO
DROP TABLE t
GO
</pre>