Create new table from SELECT with MAX condition using SQL Server - sql

I have a book table with few columns and rows like below......
Later i filter pubdate column between 2000/01/01 and 2000/12/01 by grouping pub_id....with following query
select pub_id,max(pubdate) as max_date
from book
group by pub_id
having MAX(pubdate) between '2000/01/01' and '2000/12/01'
Results are below :
Now i want to shift filtered data into new table book1, and i tried following query but it ends in error !!!!
select * into book1
from
(
select pub_id,max(pubdate) as max_date
from book
group by pub_id
having MAX(pubdate) between '2000/01/01' and '2000/12/01'
)
I tried following thing and it is working
insert into existing_table
(
select pub_id,max(pubdate) as max_date
from book
group by pub_id
having MAX(pubdate) between '2000/01/01' and '2000/12/01'
)
But i want to push filtered data dynamically into new table ?
So please correct my mistake in insert into query ......
Thanks in advance !!!!!

Give an alias name
Query
select * into book1
from
(
select pub_id,max(pubdate) as max_date
from book
group by pub_id
having MAX(pubdate) between '2000/01/01' and '2000/12/01'
) x

Alias can be used to replace a column name or a table name.
In your case, table alias is needed because sql engine deal with set based logic. If you didn't put a table alias for your defined select statement, the sql engine will not know from which set it should be refer to , even your select statement is valid.
Simply put an alias name will let the sql engine to identify which table (act like a unique ID) to refer.
For instance the simple statement, "select * from TableName", the TableName works like a table alias or an Identity to refer to.
(1) It will not work if you just put "Select * from (Select * from TableName)"
(2) It will work if you put "Select * from (Select * from TableName) x".
Hopefully this explain your doubts.

Related

How to add a where clause conditioning another database to OpenQuery linked server?

I am learning about linked server in sql server and I linked the oracle database in sqlserver and ran a query successfully against the oracle linked database as below:
SELECT *
FROM OPENQUERY(DB_ORCL,'select Name, ID from OdataLink.patients')
I have a table in sql server as well that I want to use that data in a where clause of OPENQUERY above but do not know how.
Here is the query:
Select ID from PatientTable
so based on the above sql queries, I want something like this:
SELECT *
FROM OPENQUERY(DB_ORCL,'select Name, ID from OdataLink.patients')
where "--ID in OPENQUERY above" IN (Select ID from PatientTable)
Or
SELECT *
FROM OPENQUERY(DB_ORCL,'select Name, ID from OdataLink.patients where ID in (--Select ID from PatientTable)')
Update:
I tested the resolution Stu provided and it almost worked but I cannot call the column field in openquery within the external where clause
Screenshot of the error
Try an exists correlation
select *
from OpenQuery(DB_ORCL,'select Name, ID from OdataLink.patients') q
where exists (
select * from dbo.PatientTable p
where p.Id = q.Id
);

What is the "DATA" keyword in T-SQL for?

I'm working with a database in T-SQL/SQL Server 2016 at the moment which has some stored procedures containing a keyword I'm not familiar with, namely the "DATA" suffix after a query:
SELECT * FROM dbo.TableName DATA
I'm struggling to find any documentation on what the purpose of this "DATA" keyword is. Could someone shed some light please?
It is not some specific keyword. It is just a table alias. Note that if you changed your select to
SELECT DATA.* FROM dbo.TableName DATA
it will work, as the table now has the "DATA" alias. For the same reason, this:
SELECT dbo.TableName.* FROM dbo.TableName DATA
will throw an error.
This is an alias for the table name, usually it is used if we are inner joining the same table more than one time, or when we need to call the table with a shortcut name.
For example if the table has a key named ID, then:
SELECT DATA.* FROM dbo.TableName DATA
where DATA.ID = "1"
is like
SELECT dbo.TableName.* FROM dbo.TableName
where TableName .ID = "1"

Return each name and other field corresponding to maximal value of third field in SQL

I currently have the table as follows on the picture.
I would like to write a query which returns all the names and the travel_date with the maximal 'total' value for each name. For example, I would like the query to return in this case:
Armand 2012-07-18 and Elish 2012-06-18. How could I do that ? Thanks in advance
In most cases, you'll find that the procedure for this is relatively universal. The following example will work in MySQL, MSSQL and DB2 (among others).
SELECT
a.name,
a.travel_date,
a.total
FROM test_table AS a
INNER JOIN ( SELECT `name`, MAX(total) AS `total` FROM test_table GROUP BY `name` ) AS b
ON a.name = b.name
AND a.total = b.total;
Here's an example of the sample data I worked with including the results after running the query.
-
Edit: As jarlh, the initial query I wrote was indeed wrong. The following query should provide the results that you requested in the comment below.
SELECT name, MAX(travel_date)
FROM my_table
GROUP BY name;

Join Table to Another Table then to Itself

I'm using PowerBuilder 12.5 Connected to Oracle 9. I want to select join my employee table to an employee_position table by emp_nbr, then use that emp_nbr to join into the employee table again.
However, I do not want to use the employee_copy table as I did below, since it will be taken down soon. Here's an image that illustrates what I want to do. :
I'm not sure if I should use nested selects or if this is possible only with inner joins. So this SQL code works, and I successfully retrieve the supervisor's name:
SELECT "EMPLOYEE"."EMP_NBR",
"EMPLOYEE"."DEPT_NBR",
"EMPLOYEE"."SHOP",
"EMPLOYEE"."LAST_NAME",
"EMPLOYEE"."FIRST_NAME",
"EMPLOYEE"."MIDDLE_INITIAL",
"EMPLOYEE"."EMP_CLASS",
"EMPLOYEE_POSITION"."EMP_SUPERVISOR_ID",
"EMPLOYEE_COPY"."LAST_NAME",
"EMPLOYEE_COPY"."FIRST_NAME",
"EMPLOYEE_COPY"."MIDDLE_INITIAL"
FROM "EMPLOYEE",
"EMPLOYEE_POSITION",
"EMPLOYEE_COPY"
WHERE ( "EMPLOYEE"."EMP_NBR" = "EMPLOYEE_POSITION"."EMP_NBR" ) and
( "EMPLOYEE_POSITION"."EMP_SUPERVISOR_ID" = "EMPLOYEE_COPY"."EMP_NBR" )
So my question is: How can I do this without using the employee_copy table? Also, this has to be done in one SQL query.
No problem: A self-join will work fine:
SELECT "EMPLOYEE"."EMP_NBR",
"EMPLOYEE"."DEPT_NBR",
"EMPLOYEE"."SHOP",
"EMPLOYEE"."LAST_NAME",
"EMPLOYEE"."FIRST_NAME",
"EMPLOYEE"."MIDDLE_INITIAL",
"EMPLOYEE"."EMP_CLASS",
"EMPLOYEE_POSITION"."EMP_SUPERVISOR_ID",
"EMPLOYEE_MGR"."LAST_NAME" as mgr_last_name,
"EMPLOYEE_MGR"."FIRST_NAME" as mgr_first_name,
"EMPLOYEE_MGR"."MIDDLE_INITIAL" as mgr_last_name
FROM "EMPLOYEE",
"EMPLOYEE_POSITION",
"EMPLOYEE" EMPLOYEE_MGR
WHERE ( "EMPLOYEE"."EMP_NBR" = "EMPLOYEE_POSITION"."EMP_NBR" ) and
( "EMPLOYEE_POSITION"."EMP_SUPERVISOR_ID" = "EMPLOYEE_MGR"."EMP_NBR" )
Just use an alias for the EMPLOYEE table of EMPLOYEE_MGR.

Querying the Result set of a Previous Query

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.
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.
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
You need WITH clause. The Syntax Is-
WITH someName AS(
//Your Db Query
)
SELECT * FROM someName // OR Whatever you want
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