Hide column from a left join select - sql

Struggling a little on this, hopefully I can get some answers here. I am trying to remove a column that appears in my results from the SQL command. I don't want 'player_id' to be showing up twice (the second time it shows is coming from the below join statement). Tried manipulating the join statement but everytime I do, it fails to then fetch the data.
select * from org_members
left join (select player_id, LISTAGG(ship_name, ', ') WITHIN GROUP
(order by ship_name) as Ships
from member_ships
group by player_id) ships
on org_members.player_id=ships.player_id
Just as an FYI, running this through APEX on oracle 11gXE.
EDIT: here is hte output

If you don't want player_id, then the safest thing is to list the columns that you do want.
However, there is a short-hand if you want to use *:
select *
from org_members om left join
(select player_id,
LISTAGG(ship_name, ', ') WITHIN GROUP (order by ship_name) as Ships
from member_ships
group by player_id
) ships
using (player_id);
The using clause does exactly what you want.
In your case, though, I would still be explicit about the columns:
select om.*, ships.ships
from org_members om left join
(select player_id,
LISTAGG(ship_name, ', ') WITHIN GROUP (order by ship_name) as Ships
from member_ships
group by player_id
) ships
using (player_id);

Not sure unless you show your current output but instead you should say like below. Unless you select the column it shouldn't appear twice.
select org_members.* from org_members
Per your comment, in that case you should manually specify the column names instead of using * like
select org_members.player_id,.....,ships.name,....

Related

How to join in SQL-SERVER

I am trying to learn SQL-SERVER and I have created the below query:
WITH T AS
(
SELECT ROW_NUMBER() OVER(ORDER BY d.DIALOG_ID) as row_num, *
FROM test.db as d
INNER JOIN test.dbs as ds
ON d.DIALOG_ID = ds.DIALOG_ID
)
SELECT *
FROM T
WHERE row_num <=10;
I found that the only way to limit is with ROW_NUMBER().
Although when I try to run the join I have this error:
org.jkiss.dbeaver.model.sql.DBSQLException: SQL Error [8156] [S0001]: The column 'DIALOG_ID' was specified multiple times for 'T'.
The problem: In the WITH, you do SELECT * which gets all columns from both tables db and dbs. Both have a column DIALOG_ID, so a column by that name ends up twice in the result set of the WITH.
Although until here that is all allowed, it is not good practice: why have the same data twice?
Things go wrong when SQL Server has to determine what SELECT * FROM T means: it expands SELECT * to the actual columns of T, but it finds a duplicate column name, and then it refuses to continue.
The fix (and also highly recommended in general): be specific about the columns that you want to output. If T has no duplicate columns, then SELECT * FROM T will succeed.
Note that the even-more-pure variant is to also be specific about what columns you select from T. By doing that it becomes clear at a glance what the SELECT produces, instead of having to guess or investigate when you look at the query later on (or when someone else does).
The updated code would look like this (fill in your column names as we don't know them):
WITH T AS
(
SELECT
ROW_NUMBER() OVER(ORDER BY d.DIALOG_ID) as row_num,
d.DIALOG_ID, d.SOME_OTHER_COL,
ds.DS_ID, ds.SOME_OTHER_COL_2
FROM test.db AS d
INNER JOIN test.dbs AS ds ON d.DIALOG_ID = ds.DIALOG_ID
)
SELECT row_num, DIALOG_ID, SOME_OTHER_COL, DS_ID, SOME_OTHER_COL_2
FROM T
WHERE row_num <= 10;
WITH T AS
(
SELECT ROW_NUMBER() OVER(ORDER BY d.DIALOG_ID) as row_num, d.*
FROM test.db as d
INNER JOIN test.dbs as ds
ON d.DIALOG_ID = ds.DIALOG_ID
)
SELECT *
FROM T
WHERE row_num <=10;

Count() how many times a name shows up in a table with the rest of info

I have read in various websites about the count() function but I still cannot make this work.
I made a small table with (id, name, last name, age) and I need to retrieve all columns plus a new one. In this new column I want to display how many times a name shows up or repeats itself in the table.
I have made test and can retrieve but only COLUMN NAME with the count column, but I haven't been able to retrieve all data from the table.
Currently I have this
select a.n_showsup, p.*
from [test1].[dbo].[person] p,
(select count(*) n_showsup
from [test1].[dbo].[person])a
This gives me all data on output but on the column n_showsup it gives me just the number of rows, now I know this is because I'm missing a GROUP BY but then when I write group by NAME it shows me a lot of records. This is an example of what I need:
You can use window functions, if you RDBMS supports them:
select t.*, count(*) over(partition by name) n_showsup
from mytable t
Alternatively, you can join the table with an aggregation query that counts the number of occurences of each name:
select t.*, x.n_showsup
from mytable t
inner join (select name, count(*) n_showsup from mytable group by name) x
on x.name = t.name
While the window function approach (#GMB's answer) is the right way to go, thinking through this from a subquery approach (like you were headed towards) would look something like:
select p.*, a.n_showsup
from [test1].[dbo].[person] p
INNER JOIN (
select name, count(*) n_showsup
from [test1].[dbo].[person]
GROUP BY name
) a ON p.name = a.name
This is VERY close to what you had, the difference is that we are grouping that subquery by name (so we get a count by name) and we can use that in the join criteria which we do with the ON clause on that INNER JOIN.
You should really never ever use a comma in your FROM clause. Instead use a JOIN.

Get a new column with updated values, where each row change in time depending on the actual column?

I have some data that includes as columns an ID, Date and Place denoted by a number. I need to simulate a real time update where I create a new column that says how many different places are at the moment, so each time a new place appear in the column, the new column change it's value and shows it.
This is just a little piece of the original table with hundreds of millions of rows.
Here is an example, the left table is the original one and the right table is what I need.
I tried to do it with this piece of code but I cannot use the function DISTINCT with the OVER clause.
SELECT ID, Dates, Place,
count (distinct(Place)) OVER (PARTITION BY Place ORDER BY Dates) AS
DiffPlaces
FROM #informacion_prendaria_muestra
order by ID;
I think it will be possible by using DENSE_RANK() in SQL server
you can try this
SELECT ID, Dates, Place,
DENSE_RANK() OVER(ORDER BY Place) AS
DiffPlaces
FROM #informacion_prendaria_muestra
I think you can use a self join query like this - without using windows functions -:
select
t.ID, t.[Date], t.Place,
count(distinct tt.Place) diffPlace
from
yourTable t left join
yourTable tt on t.ID = tt.ID and t.[Date] >= tt.[Date]
group by
t.ID, t.[Date], t.Place
order by
Id, [Date];
SQL Fiddle Demo

How to "pick" random records with T-SQL

This is a simple question that is actually hard to answer, because the "picking" has a special meaning.
I need to give three random picks for each person (and give pick/row number of 1, 2, and 3). What makes it hard is that the persons and picks are from different tables and there is no logical joining between the person and picks.
The closest I can get is:
SELECT TOP 15 database_id, create_date, RowNo, cs.name FROM sys.databases
CROSS apply (
SELECT top 3 Row_number()OVER(ORDER BY (SELECT NULL)) AS RowNo,*
FROM (SELECT top 3 name from sys.all_views ORDER BY NEWID()) T
) cs
I know the above is not person and picks, but it a working SQL that anyone can test it out without creating person and picks tables first. And,
It illustrates the problem I'm facing --
the above SQL will give each person the same picks, whereas I need to give different person different picks.
How to do that? Thx.
Adding a correlated condition inside the CROSS APPLY will solve your problem
SELECT TOP 15 database_id,
create_date,
RowNo,
cs.NAME
FROM sys.databases d
CROSS apply (SELECT TOP 3 Row_number() OVER(ORDER BY (SELECT NULL)) AS RowNo, *
FROM (SELECT TOP 3 NAME
FROM sys.all_views v
WHERE d.NAME = d.NAME --Here
ORDER BY Newid()) T) cs
Check the alias name in Where clause both LHS and RHS are from same table and same column it is just to execute the sub-query for each row in databases table
Modifying your own answer slightly will do the job. Check this.
SELECT TOP 15 database_id, create_date, RowNo, cs.name FROM sys.databases
CROSS apply (
SELECT top 3 Row_number()OVER(ORDER BY NEWID()) AS RowNo,*
FROM (SELECT top 3 name from sys.all_views ORDER BY NEWID()) T
) cs
The only change that I have done is to replace the NULL with NEWID().
Random function is available in Sql language could use it to randomly pick a record id in a range of record ids found in the source table.
In a newer sql version I think this may work but I can't test it currently. Older sql version will not support the by rand() command. Try this let me know if it works. Later this week I can get you something that will work on sql 2000 and up. I had to do this years ago. Let me know if this works on your Sql 2008.
select top 3 from table_name order by rand()

clubbing multiple "With" clauses in sql

I am using oracle database 10g and trying to compute the Upper control limit and lower control limit for the data set.Though it seems useless for phone number values but I am just trying to use it as a learning experience.The output should have a row wise form for entries of:-
salutation,zip,lcl and ucl value
which would allow better understanding of data.
with q as(
select student_id,salutation,zip,first_name,last_name from tempTable)
with r as(
select avg(phone) as average,stddev(phone) as sd from tempTable)
select salutation,zip,average-3*sd as"lcl",average+3*sd as"UCL"
from
q ,r
error given is select statement missing.Please tell me what is wrong I am a sql newbie and can't do it myself
while using stacked CTE expect for the first CTE you don't need With keyword instead use comma before the CTE name. Try this syntax.
WITH q
AS (SELECT student_id,
salutation,
zip,
first_name,
last_name
FROM temptable),
r
AS (SELECT Avg(phone) AS average,
STDDEV(phone) AS sd
FROM temptable)
SELECT salutation,
zip,
average - 3 * sd AS"lcl",
average + 3 * sd AS"UCL"
FROM q Cross Join r;
I don't think you need a WITH clause at all to run such a query. It might be better to use the AVG() and STDDEV() functions as window functions (analytic functions in Oracle lingo):
SELECT temp1.*, average - 3 * sd AS lcl, average + 3 * sd AS ucl
FROM (
SELECT student_id, salutation, zip, first_name, last_name
, AVG(phone) OVER ( ) AS average, STDDEV(phone) OVER ( ) AS sd
FROM tempTable
) temp1
You don't even need the subquery but it helps save some keystrokes. See this SQL Fiddle demo with dummy data from DUAL.
P.S. You do need the alias (in this case, temp1) for the subquery if you want to use * to get all the columns selected in the subquery - it won't work otherwise. Alternately you could name the columns explicitly, which is a good practice anyway.