SQL Duplicate Row Results - sql

I have a very simple select query which is being used to create an input file for a piece of software. I have the query pulling all the required fields, however I need to replicate the results six times with a hard coded ID number (1,2,3,4,5,6).
I have seen CROSS APPLY and PIVOT but the problem is the column I need to use for these doesn't exist as I'm hard coded then number.
Any help would be much appreciated.
Thanks in Advance

Maybe like this:
select CJ.ID,T.* from dbo.Table T
CROSS JOIN
(select 1 ID UNION ALL select 2 ID UNION ALL select 3 ID UNION ALL select 4 ID UNION ALL select 5 ID UNION ALL select 6 ID) CJ

Bit of a pure guess here, but are you saying that every row in your table needs to be repeated 6 times with the ID 1-6? If so, you can use a CTE of the values 1-6 and CROSS APPLY to that.
WITH Nums AS(
SELECT *
FROM (VALUES (1),(2),(3),(4),(5),(6)) V(N))
SELECT *
FROM YourTable YT
CROSS APPLY Nums;

Related

Find missing values in a sequence (sql)

Table1
Empid number
----------------
100 1
100 2
100 4
100 5
100 6
101 1
I'm self learning SQL, and a task I've come across is finding the missing values in sequence up to 12 and out putting which empid is associated.
I've attempted an approach that takes the above table and starts like
SELECT a number +1 , Min("through), MIn(by number) - 1
The entire approach use the existing numbers to find the missing "next/previous number. I'm able to output which numbers are missing. However I do not know how to group it with the associated id.
I also feel like I've complicated the task, I'm looking for guidance from anyone who can help on the best / most efficient way of going about this
Assuming that all empids and numbers are in the table somewhere, you can do this with a cross join and filter. In MS Access, this looks like:
select e.empid, n.number
from (select distinct empid from t) as e,
(select distinct number from t) as n
where not exists (select 1
from t
where t.empid = e.empid and t.number = n.number
);
This will not quite work for the data you have supplied. To handle that situation, you need a table that has the 12 numbers you are looking for.
Assumes you create a numbers table having Number column with 12 records value 1 to 12.
SELECT N.*, E.*
FROM NUMBERS N
CROSS JOIN (SELECT Distinct EmpID FROM table1) E
LEFT JOIN table1 T
on T.EmpID = E.EmpID
and T.Number = N.Number
WHERE T.EmpID is null
or substitute a derrived table for numbers table above
something like
(Select 1 as Number UNION ALL
Select 2 as Number UNION ALL
Select 3 as Number UNION ALL
Select 4 as Number UNION ALL
Select 5 as Number UNION ALL
Select 6 as Number UNION ALL
Select 7 as Number UNION ALL
Select 8 as Number UNION ALL
Select 9 as Number UNION ALL
Select 10 as Number UNION ALL
Select 11 as Number UNION ALL
Select 112 as Number)
I cant remember if MS Access will let you do this though...

Run a query with out a subquery to yield results

'MotorVehicles' Table
I ran a query to find 'AVG(Price) * 2' of attached table, then I ran another query where I substituted 'AVG(Price) * 2' with a hard number, I was able to get the two records in the result table, I have tried to use the aggregate functions in a 'Having' clause but my result table comes back empty. Need some help I would like to formulate a SELECT statement without a subquery to find all Motor vehicles whos price is more or equal to 'AVG(Price * 2)' in attached table.
thanks in advance
Many methods, this isn't nice, but it would work:
;with cte_a as
(
select avg(Price)*2 [Average]
from yourTable
-- or whatever your query to get average is as long as only 1 result
)
select *
from yourTable yt
inner join cte_a a on 1 = 1
where price >= a.Average
select * from MotorVehicles where price > (select avg(price) from t)*2;
I apologise if this is the subquery you want to avoid.
You can get something similar using a partitioned AVG().
DECLARE #T TABLE
(
X INT
)
INSERT #T SELECT 1
INSERT #T SELECT 10
INSERT #T SELECT 15
INSERT #T SELECT 20
SELECT X,XAVG=AVG(X) OVER(PARTITION BY 1 ) FROM #T
Resulting in:
X XAVG
1 11
10 11
15 11
20 11

Selecting a sequence in SQL

There seems to be a few blog posts on this topic but the solutions really are not so intuitive. Surely there's a "Canonical" way?
I'm using Teradata SQL.
How would I select
A range of number
A date range
E.g.
SELECT 1:10 AS Nums
SELECT 1-1-2010:5-1-2014 AS Dates1
The result would be 10 rows (1 - 10) in the first SELECT query and ~(365 * 3.5) rows in the second?
The "canonical" way to do this in SQL is using recursive CTEs, which the more recent versions of Teradata support.
For your first example:
with recursive nums(n) as (
select 1 as n
union all
select n + 1
from nums
where n < 10
)
select *
from nums;
You can do something similar for dates.
EDIT:
You can also do this by using row_number() and an existing table:
with nums(n) as (
select n
from (select row_number() over (order by col) as n
from ExstingTable t
) t
where n <= 10
)
select *
from nums;
ExistingTable is just any table with enough rows. The best choice of col is the primary key.
with digits(n) as (
select 1 as n union all select 2 union all select 3 union all select 4 union all select 5 union all
select 6 union all select 7 union all select 8 union all select 9 union all select 10
)
select *
from digits;
If your version of Teradata supports multiple CTEs, you can build on the above:
with digits(n) as (
select 1 as n union all select 2 union all select 3 union all select 4 union all select 5 union all
select 6 union all select 7 union all select 8 union all select 9 union all select 10
),
nums(n) as (
select d1.n*100 + d2.n*10 + d3.n
from digits d1 cross join digits d2 cross join digits d3
)
select *
from nums;
In Teradata you can use the existing sys_calendar to get those dates:
SELECT calendar_date
FROM sys_calendar.CALENDAR
WHERE calendar_date BETWEEN DATE '2010-01-01' AND DATE '2014-05-01';
Note:
DATE '2010-01-01' is the only recommended way to write a date in Teradata
There's probably another custom calendar for the specific business needs of your company, too. Everyone will have access rights to it.
You might also use this for the range of numbers:
SELECT day_of_calendar
FROM sys_calendar.CALENDAR
WHERE day_of_calendar BETWEEN 1 AND 10;
But you should check Explain to see if the estimated number of rows is correct. sys_calendar is a kind of template and day_of_calendar is a calculated column, so no statistics exists on that and Explain will return an estimated number of 14683 (20 percent of the number of rows in that table) instead of 10. If you use it in additional joins the optimizer might do a bad plan based on that totally wrong number.
Note:
If you use sys_calendar you are limited to a maximum of 73414 rows, dates between 1900-01-01 and 2100-12-31 and numbers between 1 and 73414, your business calendar might vary.
Gordon Linoff's recursive query is not really efficient in Teradata, as it's a sequential row-by-row processing in a parallel database (each loop is an "all-AMPs step" in Explain) and the optimizer doesn't know how many rows will be returned.
If you need those ranges regularly you might consider creating a numbers table, I usually got one with a million rows or I use my calendar with the full range of 10000 years :-)
--DROP TABLE nums;
CREATE TABLE nums(n INT NOT NULL PRIMARY KEY CHECK (n BETWEEN 0 AND 999999));
INSERT INTO Nums
WITH cte(n) AS
(
SELECT day_of_calendar - 1
FROM sys_calendar.CALENDAR
WHERE day_of_calendar BETWEEN 1 AND 1000
)
SELECT
t1.n +
t2.n * 1000
FROM cte t1 CROSS JOIN cte t2;
COLLECT STATISTICS COLUMN(n) ON Nums;
The COLLECT STATS is the most important step to get correct estimates.
Now it's a simple
SELECT n FROM nums WHERE n BETWEEN 1 AND 10;
There's also a nice UDF on GitHub for creating sequences which is easy to use:
SELECT DATE '2010-01-01' + SEQUENCE
FROM TABLE(gen_sequence(0,DATE '2014-05-01' - DATE '2010-01-01')) AS t;
SELECT SEQUENCE
FROM TABLE(gen_sequence(1,10)) AS t;
But it's usually hard to convince your DBA to install any C-UDFs and the number of rows returned is unknown again.
sequence 1 to 10
sel sum (1) over (ROWS UNBOUNDED PRECEDING) as seq_val
from sys_calendar.CALENDAR
qualify row_number () over (order by 1)<=10

How can I identify common elements in at least 2 out of 5 tables?

If I have 5 tables, what join functions should I be using if I want to find elements in a single column that occur in AT LEAST 2 out of the 5 tables?, ie: discarding only those elements that occur in a single table.
Would the code be similar if I wanted to find common elements in AT LEAST 3/5 tables?
(I'm using MS Access)
Thanks!
I'm not 100% positive I understand your question, but I think you can use UNION ALL for this:
select yourcol
from (
select distinct yourcol from t1
union all
select distinct yourcol from t2
union all
select distinct yourcol from t3
union all
select distinct yourcol from t4
union all
select distinct yourcol from t5
) t
group by id
having count(*) >= 2
SQL Fiddle Demo
Then you can change >= 2 to whatever number you want.
BTW -- if the column in question doesn't contain duplicates, you can remove distinct from the subquery.

CTE after UNION ALL

This query does not work:
WITH a AS
(SELECT 1 AS c1)
SELECT
*
FROM
a
UNION ALL
WITH b AS
(SELECT 1 AS c1)
SELECT
*
FROM
b
Could you help, please?
Real query uses tables, but it is not essential in the example.
Many thanks
;WITH a AS
(SELECT 1 AS c1),
b AS
(SELECT 1 AS c1)
SELECT
*
FROM
a
UNION ALL
SELECT
*
FROM
b
Simple answer: you're breaking the query ;-)
Let me explain:
The UNION key word takes 2 "queries" and makes them into one.
The WITH key word can't be used inside a query and it is only valid for one query
WITH can be used to define multiple CTEs
The result of all of these is that you want to define both of the CTEs (a & b) before the UNION query.
Putting the WITH inside the UNION query breaks the UNION (since WITH is always outside of (before) a query.