SQL Select within select

Posted on 2011-10-20
Last Modified: 2013-12-16

select * from  --this is an example the star will be replaced with desired columns

--these next two selects work perfectly, they return the desired rows
--I would like to use their results in the outer select
--However, I get this error
--Msg 8156, Level 16, State 1, Line 18
--The column 'machine_id' was specified multiple times for 'finalResult'.
--Thank you for your input.

select * from [UpdateHistory] as i
inner join
(select u.machine_id, u.application_id, max(servertimestamp) as [timestamp]
from [UpdateHistory] u      
group by machine_id, application_id) p
i.machine_id = p.machine_id AND
i.application_id = p.application_id AND
i.servertimestamp = p.[timestamp]

) as finalResult
Question by:wilfordrocks
    1 Comment
    LVL 23

    Accepted Solution

    If your sub-query is returning more than one column with the same name, this error could occur

    eg: - In 'users' table, i have a column 'user_id. * means it fetches all records, right - which includes user_id as well. In addition to that I have mentioned user_id again.
    select * from
    select *, user_id from users
    ) a

    Open in new window


    Featured Post

    What Should I Do With This Threat Intelligence?

    Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

    Join & Write a Comment

    If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
    Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
    This tutorial will give a an overview on how to deploy remote agents in Backup Exec 2012 to new servers. Click on the Backup Exec button in the upper left corner. From here, are global settings for the application such as connecting to a remote Back…
    This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles to another domain controller. Log onto the new domain controller with a user account t…

    754 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now