Quantcast
Channel: Forum Getting started with SQL Server
Viewing all articles
Browse latest Browse all 4729

In a query, can I refer to a subquery column elsewhere in the query?

$
0
0

Is there a way to refer to a subquery column from elsewhere in a query?

In my case I am generating the MIN and MAX of a column in the child table. For the convenience of the statistics consumers, I would also like to provide a column identifying the difference between the MIN and MAX values.

Here's the proof-of-concept SQL:

-- Check for previous version of table to be generated
-- and delete it if it exists
IF OBJECT_ID('dbo.Parent', 'U') IS NOT NULL
    DROP TABLE dbo.Parent;

CREATE TABLE dbo.Parent (
        ParentID varchar(3) NOT NULL,
        ParentDesc varchar(25) NOT NULL
        );

INSERT INTO dbo.Parent values ('P1', 'Parent Rec 1');
INSERT INTO dbo.Parent values ('P2', 'Parent Rec 2');
INSERT INTO dbo.Parent values ('P3', 'Parent Rec 3');

--Create and populate second table
IF OBJECT_ID('dbo.Child', 'U') IS NOT NULL
    DROP TABLE dbo.Child;

CREATE TABLE dbo.Child (
        ParentID varchar(3) NOT NULL,
        ChildID varchar(3) NOT NULL,
        ChildDesc varchar(25) NOT NULL,
        ChildValue numeric(3,1) NOT NULL
        );

INSERT INTO dbo.Child values ('P1', 'C1', 'Child Rec 1',1.1);
INSERT INTO dbo.Child values ('P2', 'C1', 'Child Rec 2',1.2);
INSERT INTO dbo.Child values ('P2', 'C2', 'Child Rec 3',2.2);
INSERT INTO dbo.Child values ('P3', 'C1', 'Child Rec 4',1.3);
INSERT INTO dbo.Child values ('P3', 'C2', 'Child Rec 5',2.3);
INSERT INTO dbo.Child values ('P3', 'C3', 'Child Rec 6',3.3);

-- Perform query

SELECT P.ParentID,
       (SELECT MIN(ChildValue)
        FROM dbo.Child
        WHERE P.ParentID = dbo.Child.ParentID) as MinChildValue,
       (SELECT MAX(ChildValue)
        FROM dbo.Child
        WHERE P.ParentID = dbo.Child.ParentID) as MaxChildValue,
--
--     The following line is the one that's causing the problem
--
       (MaxChildValue - MinChildValue) as ChildValueDifference
FROM   dbo.Parent P,
       dbo.Child  C
WHERE  P.ParentID = C.ParentID
GROUP BY P.ParentID
;

What I get back is the following error message:

Msg 207, Level 16, State 1, Line 41
Invalid column name 'MaxChildValue'.
Msg 207, Level 16, State 1, Line 41
Invalid column name 'MinChildValue'.


Viewing all articles
Browse latest Browse all 4729

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>