SQL Two fields from tables of unassociated data into the same field? - sql

I am trying to do this is SQL:
-------------------------------
Table A
-------------------------------
ID | Title
1 | Something Groovy
2 | Something Else
-------------------------------
Table B
-------------------------------
ID | Title
1 | Something Different
2 | Something More
Awesome Select Statement
-------------------------------
Both in one field
-------------------------------
Title
Something Groovy
Something Else
Something Different
Something More
Any Ideas?

Use UNION ALL to obtain the union of two selects. If you want to eliminate duplicates, use simply UNION.
SELECT Title FROM TableA
UNION ALL
SELECT Title FROM TableB

This is a simple union:
Select title from TableA
UNION
Select title from TableB
Note that any items that are identical will be eliminated.

Related

group by alias in Oracle

I need get all state (1,2,3,4) with out duplicates.
1 xxx
2 yyy
3 zzz
4 jjj
My first and only idea was get all state and group them:
select state1 as state,desc1 as desc from table where id=X
Union
select state2 as state,desc2 as desc from table where id=X
This get in the example 6 rows. So, to discard the duplicate I try to use a alias:
select state,desc from
(
select state1 as state,desc1 as desc from table where id=X
Union
select state2 as state,desc2 as desc from table where id=X
)
group by state;
But I got the error is not a GROUP BY expression.
I saw similar questions but I can't resolve the problem.
All the select-list items have to either be in the group by, or be aggregates. You could include both state, desc in the group-by clause, but it would be neater to use distinct instead; however, union (without all) suppresses duplicates anyway, so neither is needed here.
As Bluefeet mentioned elsewhere, desc is a keyword and has a meaning in order-by clauses, so it is not a good name for a column or alias.
This gets four rows, not six:
select state1 as state_x, desc1 as desc_x from t42 where id = 'X'
union
select state2 as state_x, desc2 as desc_x from t42 where id = 'X';
| STATE_X | DESC_X |
|---------|--------|
| 1 | xxx |
| 2 | yyy |
| 3 | zzz |
| 4 | jjj |
SQL Fiddle. It isn't clear why you think you're getting six rows, or what you are really doing differently.
The UNION should remove any duplicates. If it doesn't then you should check the data -- maybe you have extra spaces in the text columns.
Try something like this.
select state1 as state,TRIM(desc1) as desc from table where id=X
Union
select state2 as state,TRIM(desc2) as desc from table where id=X
Your first query doesn't work probably because desc1 and desc2 columns have different types e.g. char(10) and char(20). Here is an example from SQL Fiddle that shows this effect. If you change char(20) to char(10) in the left pane the query will work.

Displaying records in the custom sequence

I want to fetch data from the database in my custom sequence.
For example if the query is;
SQL>Select * from table1 where id in(5,3,4)
So expected result would be.
Id | Name
----------
5 | John
3 | David
4 | Rock
but data is displaying in following order:
Id | Name
----------
3 | David
4 | Rock
5 | John
Can anyone help me to achieve this result?
The where clause is not relevant to the order of the results.
You can use "order by XXX" to arrange results by specific column/s,
but as I can see in your example it is not ordered by id or name.
So... I would suggest to add another column named "position" or "pos" and it will contain an integer with the desired order, than simple query with order by that column.
select *
from table1
where id in(5,3,4)
order by position
check this, it will give your wanted order
Select * from table1 where id=5
Union all
Select * from table1 where id=3
union all
Select * from table1 where id=4

SQL Creating multiple columns in View from one single table-column

I'm trying to create a View in SQL Server 2008 R2, where data is extracted from two tables with dual one-to-one relationships, and I want to create two columns in the view based values from a single column in one of the tables.
The tables are currently similar to these examples:
TableA:
PrimaryKey | Name | Value_FK | Number_FK
-------------------------------------------
66 | NameA | 1 | 2
77 | NameB | 3 | 4
TableB:
PrimaryKey | Value
-------------------
1 | 238
2 | 456
3 | 100
4 | 200
The View should look like this:
Name | Value | Number
-------------------------
NameA | 238 | 456
NameB | 100 | 200
('Value' and 'Number' are essentially the same type, and are both found in the 'Value' column in TableB. I thought it would be more easy to distingiush between 'Value' and 'Number', than 'ValueA' and 'ValueB').
The factor that should decide which values go into Column 'Value' or Column 'Number' is the PrimaryKey in TableB and its references in either foreignkey in TableA (but both FKs shall NEVER refer to the same key).
This is likely not the most brilliant database model, having dual relationships between to tables. This is however due to mapping some C#.NET classes to a database by using ADO.NET Entity Framework, where Class A has two objects of Class B (in this case named 'Value' and 'Number'), and the database model currently constructs two relationships becuase of this. Changing this is not an option.
I've tried googling this, but I find it difficult to find an answer that I need. Especially when most results are about the opposite: Selecting multiple columns into one column.
So, how should I write the Select statement?
CREATE VIEW ViewName
AS
SELECT DISTINCT a.Name as 'Name', ????? as 'Value', ????? as 'Number'
FROM TableA a, TableB b
I am quite rusty with advanced SQL-commands. It's been over 1,5 years since last I was into something this advanced. I tried something similar to this first:
CREATE VIEW ViewName
AS
WITH Name AS
( SELECT DISTINCT a.Name FROM TableA a )
Value AS
(
SELECT DISTINCT b.Value as 'Value' FROM TableA a, TableB b
WHERE b.PrimaryKey = an.ValueA_FK
),
Number AS
(
SELECT DISTINCT b.Value as 'Number'
FROM TableA a, TableB b
WHERE a.PrimaryKey = an.ValueB_PrimaryKey
)
SELECT DISTINCT
* FROM Name, Value, Number
The result of my utterly failed attempt is like this:
Name | Value | Number
-------------------------
NameA | 100 | 200
NameB | 100 | 200
NameA | 100 | 456
NameB | 100 | 456
NameA | 238 | 200
NameB | 238 | 200
NameA | 238 | 456
NameB | 238 | 456
Now, any suggestiong as what to fill in the query?
You can reference the same table more than once in the FROM clause:
SELECT a.Name as 'Name', b1.Value as 'Value', b2.Value as 'Number'
FROM TableA a
inner join TableB b1
on
a.Value_FK = b1.PrimaryKey
inner join TableB b2
on
a.Number_FK = b2.PrimaryKey
I've also removed the DISTINCT, since it shouldn't be your habit to add one, and there's nothing in the question that suggests one is necessary. I've also used ANSI-Style joins. These are almost always to be preferred over the older style (where tables in the FROM clause are just separated by commas)
If it's possible that some rows in TableA have a NULL Value_FK or Number_FK, and you still want those rows in your view, you would switch one or both of the inner joins to be left joins. You would then also decide whether the output column should be NULL (in which case you're done) or some other value (in which case, you would have e.g. COALESCE(b1.Value,<Value when null>) as 'Value').
This query will yield results you want:
select t1.Name, value.Value, number.Value as Number
from TableA t1
inner join TableB value on value.PrimaryKey = t1.Value_FK
inner join TableB number on number.PrimaryKey = t1.Number_FK
you over-complicated your query a lot.

SQL inner join two tables with the same column names

I have two tables with a variable amount of columns. (I don't know how many columns or what there names will be) for example Table A and Table B.
TableA:
ID | B_ID | {variable}
TableB
ID | {variable}
Query:
SELECT TableA.*, TableB.* FROM TableA INNER JOIN TableB ON TableA.B_ID= TableB.id;
When TableA and TableB both have a column with a same name I can't distinguish between the two different columns. For example of both tables has the column "Name" this query would result in :
ID | ID | B_ID | NAME | NAME |
1 | 35 | 35 | bob | jim |
What I am looking for is a way to differentiate between the two tables. Preferably with a prefex for the column names such as.
TableA_ID | TableB_ID | TableA_B_ID | TableA_NAME | TableB_NAME |
1 | 35 | 35 | bob | jim |
I know of the "AS" keyword but the problem is that I don't know what the column names are going to be before hand. (I don't know if TableA or TableB are going to have the column Name)
So my question is
How do you differentiate the columns between the two tables with a INNER JOIN when the tables may have the same column names ?
I am using SQLite3.
Your result set (given your query) should have all of the TableA columns followed by all the TableB colums, so when you get to the second ID colum, you know you're into the TableB data.
That said, it is would seem odd to me that you're querying all the data out of two tables about which you know functionally nothing...
This is admittedly a hack solution, but this:
SELECT TableA.*, "#", TableB.*
FROM TableA INNER JOIN TableB ON TableA.B_ID= TableB.id;
Would produce a list of results which would be divided in two blocks, left and right of the # column.

Is it possible in sql to group by fields matching some pattern?

Is it possible in SQL to do grouping by LIKE patterns? I would like to achieve something like this:
id|name
1 | Mike
2 | Bob
3 | Bill
4 | Alice
and then doing query like: SELECT name from users group by _pattern_
For example I would like to get groups by matching patterns 'B*', '*l*' and 'Mike'
would give the output:
B* | Bob
| Bill
*l* | Bill
| Alice
Mike| Mike
Select 'B*' as Mask, Name
from Table
WHERE Name like 'B%'
UNION ALL
Select '*l*' as Mask, Name
from Table
WHERE Name like '%l%'
UNION ALL
Select 'Mike' as Mask, Name
from Table
WHERE Name like 'Mike'
If you want the same record to appear multiple times according to the pattern it matches, you should use multiple SELECT statements with the relevant filters and UNION them together..
You can query against the patterns in a set structure then GROUP BY or DISTINCT to remove dups, below is a way with an MSSQL CTE (temp table/table var would work also);
with match (pattern) as (
select 'B%'
union select '%l%'
union select 'Mike'
)
select
pattern,
name
from TABLE, match where TABLE.name like match.pattern
group by pattern, name
==
%l% Alice
%l% Bill
B% Bill
B% Bob
Mike Mike