Querying the Result set of a Previous Query

坚强是说给别人听的谎言 提交于 2019-12-31 04:03:07

问题


I have a query for example Query1 = Select Name from table where some Criteria. Now this query returns a result set of course, what I want is to query the result set of this query, for example I only want the unique Names from the above query select Distinct(Name) from Query1. I should mention that I know I can just use distinct in Query1 but this is just an example my real scenario is somewhat different, what I want to know is whether it's possible to query the result set of a previous query. I am using SQL Server 2012.


回答1:


You can use the WITH clause

WITH SomeClients AS (
    SELECT
        c.ID
    FROM Clients c
    WHERE c.Name LIKE '%hello%'
)

SELECT DISTINCT
    sc.ID
FROM SomeClients sc



回答2:


There are several ways to solve this:

1: create a view from the first query and run the second query on the view.

2: nest both queries, like this:

SELECT DISTINCT [Name]
FROM (
  SELECT [Name] 
  FROM table 
  WHERE some Criteria
) As InnerQuery

3: use a temporary table to store the resultset of the first query as suggested by wewesthemenace in the comments.

4: use CTE as suggested the thebreiflabb in the other answer to this post.

Personally, I would probably go with the first or second option, depending if you need to use the first query as stand alone as well.




回答3:


You need WITH clause. The Syntax Is-

WITH someName AS(
 //Your Db Query
)
SELECT * FROM someName // OR Whatever you want



回答4:


you can create a table to store the results temporarily and use that table in a new query

DECLARE @resultset table (
    ID   int identity(1,1) not null
  , name nvarchar(100)
)

Select top 50 application_Name
into  resultset
from Applications_ASIS


来源:https://stackoverflow.com/questions/29362693/querying-the-result-set-of-a-previous-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!