ahmd0
ahmd0

Reputation: 17313

Struggling to count and order by a column by reference in T-SQL database

I'm not sure if I'm writing the following SQL statement correctly? (Using T-SQL)

I have two tables:

Table 1: [dbo].[t_Orgnzs]

[id] = INT
[nm] = NVARCHAR(256)

Table 2: [dbo].[t_Usrs]

[id] = INT
[ds] = NVARCHAR(256)
[oid] = INT (referenced [dbo].[t_Orgnzs].[id])

I need to select elements from Table 2, ordered by the [oid] column ascending from 1 to 16, but the catch is that the [oid] references a string in the Table 1, that I actually need to return as a result.

So for say, if tables were laid out like so: Table 1:

id   nm
1    Name 1
2    Name 2
3    Name 3
4    Name 4

And Table 2:

id   ds      oid
1    A       2
2    B       4
3    C       1

The resulting query must return:

3 C Name 1
1 A Name 2
2 B Name 4

So here's the SQL I'm using:

WITH ctx AS (
  SELECT [id],
         [ds],
         (SELECT [nm] FROM [dbo].[t_Orgnzs] WHERE [id]=[dbo].[t_Usrs].[oid]) AS organizName,
         ROW_NUMBER() OVER (ORDER BY organizName ASC) AS rowNum 
  FROM [dbo].[t_Usrs]
            )
             SELECT [id], [ds], organizName 
             FROM ctx 
             WHERE rowNum>=1 AND rowNum<=16;

And I'm getting an error: "Invalid column name 'organizName'."

Upvotes: 1

Views: 156

Answers (3)

Mosty Mostacho
Mosty Mostacho

Reputation: 43494

SELECT TOP 16 * FROM [t_Orgnzs] 
INNER JOIN [t_Usrs]
ON [t_Orgnzs].[id] = [t_Usrs].[oid] 
ORDER BY [oid]

Upvotes: 0

Smarty
Smarty

Reputation: 1579

I do not understand the meaning of use ROW_NUMBER() in your case. Why?

CREATE TABLE [t_Orgnzs] ([id] int PRIMARY KEY, [nm] NVARCHAR(256))
GO

CREATE TABLE [t_Usrs] ([id] int, [ds] NVARCHAR(256), [oid] int FOREIGN KEY REFERENCES [t_Orgnzs]([id]))
GO

INSERT [t_Orgnzs] VALUES (1,'Name_1')
INSERT [t_Orgnzs] VALUES (2,'Name_2')
INSERT [t_Orgnzs] VALUES (3,'Name_3')
INSERT [t_Orgnzs] VALUES (4,'Name_4')
GO

INSERT [t_Usrs] VALUES (1,'A',2)
INSERT [t_Usrs] VALUES (2,'B',4)
INSERT [t_Usrs] VALUES (3,'C',1)
GO

SELECT * 
FROM [t_Orgnzs] 
INNER JOIN [t_Usrs] ON [t_Orgnzs].[id]=[t_Usrs].[oid] 
ORDER BY [oid]

Upvotes: 1

Thit Lwin Oo
Thit Lwin Oo

Reputation: 3448

How about this one

select id, ds, nm
from
(
    select ROW_NUMBER() OVER (ORDER BY o.nm ASC) AS rowNum, u.id, u.ds, o.nm
    from t_Usrs u inner join t_Orgnzs o on (u.oid = o.id)
) t
 WHERE rowNum>=1 AND rowNum<=16;

Upvotes: 0

Related Questions