SQLite. SQL. Making row fields into column headings - sql

Tables
tblTracker: [ID, Date]
tblTrackerHours: [tblTracker.ID, Hour]
tblTrackerWTGStatus: [tblTracker.ID, TurbineID, Hour, TurbineStatus]
Desired Output
Columns: Date | Hour (from tblTrackerHours) | TurbineIDs .....>
Data: Ordered dates | 1-24 for each date | TurbineStatus
I'm struggling understand where to begin with creating an SQL statement that will do this. Not every TurbineID has an entry for each hour or each day.
Any hints welcomed :-)

I think what you need is a view, which you can create as follows:
create view desiredView as
select
t.date as DATEorWhateverYouWantToNameThisColumn,
h.hour as HOURorWhateverYouWantToNameThisColumn,
s.turbineId as TirbuneIDorWhateverYouWantToNameThisColumn,
s.turbineStatus as STATUSorWhateverYouWantToNameThisColumn
from
tblTracker t,
tblTrackerHours h,
tblTrackerWTGStatus s
where
h.id = t.id AND
s.id = t.id;
Please note that, h.id and s.id in where clause actually the columns which are foreign keys in relevant tables.You can set each column's name using a word after AS. You can find the syntax of the command here.
After you have this view, you can select from it as you wish
select * from desiredView

Related

SQL - Returning fields based on where clause then joining same table to return max value?

I have a table named Ticket Numbers, which (for this example) contain the columns:
Ticket_Number
Assigned_Group
Assigned_Group_Sequence_No
Reported_Date
Each ticket number could contain 4 rows, depending on how many times the ticket changed assigned groups. Some of these rows could contain an assigned group of "Desktop Support," but some may not. Here is an example:
Example of raw data
What I am trying to accomplish is to get the an output that contains any ticket numbers that contain 'Desktop Support', but also the assigned group of the max sequence number. Here is what I am trying to accomplish with SQL:
Queried Data
I'm trying to use SQL with the following query but have no clue what I'm doing wrong:
select ih.incident_number,ih.assigned_group, incident_history2.maxseq, incident_history2.assigned_group
from incident_history_public as ih
left join
(
select max(assigned_group_seq_no) maxseq, incident_number, assigned_group
from incident_history_public
group by incident_number, assigned_group
) incident_history2
on ih.incident_number = incident_history2.incident_number
and ih.assigned_group_seq_no = incident_history2.maxseq
where ih.ASSIGNED_GROUP LIKE '%DS%'
Does anyone know what I am doing wrong?
You might want to create a proper alias for incident_history. e.g.
from incident_history as incident_history1
and
on incident_history1.ticket_number = incident_history2.ticket_number
and incident_history1.assigned_group_seq_no = incident_history2.maxseq
In my humble opinion a first error could be that I don't see any column named "incident_history2.assigned_group".
I would try to use common table expression, to get only ticket number that contains "Desktop_support":
WITH desktop as (
SELECT distinct Ticket_Number
FROM incident_history
WHERE Assigned_Group = "Desktop Support"
),
Than an Inner Join of the result with your inner table to get ticket number and maxSeq, so in a second moment you can get also the "MAXGroup":
WITH tmp AS (
SELECT i2.Ticket_Number, i2.maxseq
FROM desktop D inner join
(SELECT Ticket_number, max(assigned_group_seq_no) as maxseq
FROM incident_history
GROUP BY ticket_number) as i2
ON D.Ticket_Number = i2.Ticket_Number
)
SELECT i.Ticket_Number, i.Assigned_Group as MAX_Group, T.maxseq, i.Reported_Date
FROM tmp T inner join incident_history i
ON T.Ticket_Number = i.Ticket_Number and i.assigned_group_seq_no = T.maxseq
I think there are several different method to resolve this question, but I really hope it's helpful for you!
For more information about Common Table Expression: https://www.essentialsql.com/introduction-common-table-expressions-ctes/

Refer to another table and return data adjacent to Max() result

I have the following two tables:
Using SQL Server 2012, I want to know the INTERVAL from the Hourly table where the MaxWaitTime and Split match what comes from the Daily table for each day. I am assuming I need to use a window function here, but I can't figure out the right answer.
There may be times where MaxWaitTime is 0 for an entire day, and thus all rows from the hourly table match. In this scenario, I would prefer a Null answer, but the earliest INTERVAL for that day would be fine.
There will also be times where multiple INTERVALs have the same wait time. In this scenario the first INTERVAL where the MaxWaitTime is present that day should be returned.
You can use outer apply if you want at most one match:
Looks like a simple left join should work between the tables. I'm simply going by the data shown above...
The query should look something like this. If the join fails, then a NULL will be returned. Give it a go..
select d.*, h.interval as maxinterval
from daily d outer apply
(select top 1 h.*
from hourly h
where convert(date, h.interval) = d.row_date and
h.split = d.split and
h.maxwaittime = d.maxwaittime
order by h.interval asc
) h;
If you want NULL for multiple matches, you can do something similar:
select d.*, h.interval as maxinterval
from daily d outer apply
(select top 1 h.callsoffered, h.split, max(h.interval) as maxinterval
from hourly h
where convert(date, h.interval) = d.row_date and
h.split = d.split and
h.maxwaittime = d.maxwaittime
group by h.maxwaittime, h.split
having count(*) = 1
) h;
Looks like a simple left join should work between the tables. I'm simply going by the data shown above...
The query should look something like this. If the join fails, then a NULL will be returned. Give it a go..
select daily.* ,hourly.callsoffered, hourly.interval as maxinterval
from daily
left join hourly
on convert(date,hourly.interval) = daily.row_date
and hourly.split = daily.split
and hourly.maxwaittime = daily.maxwaittime

SQl query group by year different columns where condition apply

I am not coming right with this.
I have this table "bids" in SQL 2012:
| custDecDate | forBid | valueXX | valueYY |
I would like to sum the values relevant "valueXX" and "ValueYY" separately and grouped per year "custDecDate" where the value of column "forBid" = For Contract
"custDecDate" is a datetime and contains date dd/MM/yyyy, valueXX and valueYY are int and "forBid" is a nvarchar.
I am very lost. Any help is welcomed, I need a starting point to learn this.
SELECT YEAR(custDecDate), SUM(valueXX), SUM(valueYY)
FROM bids
WHERE forBid = "For Contract"
GROUP BY YEAR(custDecDate)
the query should be really simple....
Oracle:
Select trunc(custDecDate,'YYYY'), sum(valueXX), sum(valueYY)
from bids
where forBid = '...'
group by trunc(custDecDate,'YYYY')
MSSQL:
Select year(custDecDate), sum(valueXX), sum(valueYY)
from bids
where forBid = '...'
group by year(custDecDate)
Did I answer what you meant?

Determine values in a database that occur before a certain date, but not after that date

I need to determine if a certain field value in a database table occurs before a certain date, but not after that date.
I can determine the values that occur before the cutoff date with a simple select, but there may be records after that date.
The field values that I am using are the 'entereddate' and the value I am looking for (in this case a carriercode).
Thanks for your help!
This is the best I can do without seeing the data structure.
SELECT *
FROM BillTBL a
INNER JOIN carriertbl b ON a.carrier_key = b.carrier_key
WHERE a.billentereddate < '2009-09-01'
AND NOT EXISTS (SELECT 1
FROM BillTBL
WHERE whatever_the_key_is = a.whatever_the_key_is
AND billentereddate > '2009-09-01')
select a.carriercode
from carriertbl as a
inner join BillTBL as b ON b.carrier_key = a.carrier_key and b.enteredate < '2009-09-01'
Maybe you have to ajust some column name...

How to do multiple join / group by selects using sqlite3?

I have a sqlite3 database with one table called orig:
CREATE TABLE orig (sdate date, stime integer, orbnum integer);
What I want to do is select the first date/time for each orbnum. The only problem is that stime holds the time as a very awkward integer.
Assuming a six-digit number, the first two digits show the hour, the 3./4. show the minutes, and the last two digits show the seconds. So a value of 12345 is 1:23:45, whereas a value of 123456 is 12:34:56.
I figured I'd do this using two nested join/group statements, but somehow I cannot get it to work properly. Here's what I've got so far:
select s.orbnum, s.sdate, s.stime
from (
select t.orbnum, t.sdate, t.stime, min(t.sdate) as minsdate
from (
select orbnum, sdate, stime, min(stime) as minstime
from scia group by orbnum, sdate
) as t inner join orig as s on s.stime = t.minstime and s.sdate = t.sdate and s.orbnum = t.orbnum
) as d inner join scia as s on s.stime = d.stime and s.sdate = minsdate and s.orbnum = d.orbnum
where s.sdate >= '2002-08-01' limit 0,200;
This is the error I get:
Error: no such column: t.orbnum
I'm sure it's just some stupid mistake, but actually, I'm quite new to SQL ...
Any help is greatly appreciated :)
Edit:
After fixing the obvious typo, the query runs -- but returns an empty result set. However, the table holds ~10yrs of data, with about 12 orbnums per day and about 4-5 different times per orbnum. So I guess there's some mistake in the logic of the query ...
In your last join, you have d, which is the result of your double nested select, and you join s on it. From there, t is not visible. That’s why you get the “no such column: t.orbnum” error. Maybe you meant s.orbnum = d.orbnum?