Ordering Data using sql - sql

I have a requirement where from a View need to get result in a specific sorting order. Here is sample table:
Now the data has to arrange in Descending order based on the last day BASE_PERCENTAGE. So Last day is 04-Feb-2017 and the highest to lowest order is Jessie, Ricky, Jammie and Jasmine. The final output should arrange data based on BASE_PERCENTAGE, CURR_DATE and Name. Like This-
Could someone please help to how to get the same result using sql. How sql can be written to that it gives the same result.
Please let me know if you need more explanation.
Attached Table_View_sql.sql is having table create, Sample Data Insert and View creation. View will give the data with BASE_Percentage.
Table View Script

You need to be able to tell on every row what the most recent date base_percentage is, if you want to be able to sort by it. One way to do that is something like this. You don't need to keep the LD.LastDayBase in the select output, I added it so you can easily see what the value is while testing.
If you know what the #LastDay is, you could pass it through to the query and skip the first line.
DECLARE #LastDay date = (select MAX(Curr_Date) from v_DailyDetails);
SELECT VD.*, LD.LastDayBase
FROM v_DailyDetails VD
LEFT OUTER JOIN
(
Select Name, BASE_PERCENTAGE LastDayBase
From v_DailyDetails VD
Where CURR_DATE = #LastDay
) LD on LD.Name = VD.Name
ORDER BY LD.LastDayBase DESC, VD.CURR_DATE DESC, LD.NAME
Note that the order you requested means that if ALICE and BOB both had the same LastDayBase value, then you would get the following order ALICE Feb4, Bob Feb4, Alice Feb3, Bob Feb3 etc. If you want days for a given name to be always together, you should use
ORDER BY LD.LastDayBase DESC, LD.NAME, VD.CURR_DATE DESC

Related

SQL- Need to Order By date first and then have a specific variable value always come first

I need to order by results to order by date first but then to have a specific variable value (trackingbasisID=4) to always be ordered first. Below is an example. I have many variables in the select statement.I've also attached the graph of how results are shown. We'd liked to avoid the W in the graph s so we want the delay (TrackingBasisID=4) to always display first over all other id's but still sort by date first. My Current OrderBy Statement is simply:
ORDER BY hd.Date ASC, hd.PreimPhaseNumber ASC
There are trackingbasis ID of 1,2,3,4,5,6 -- Of which We always want 4 to come first when being ordered.

Query to select appropriate feedback record based on dates

I understand there are many questions and answers outlining how to query data with relation to dates stored in SQL. My question, while in the same vein, is not something I've been able to find a solution for.
There is a SolutionRevisions table with three relevant columns: SR_ID (primary), SR_SolutionID, and SR_CreatedDate.
There is a Feedback table with F_ID, F_ItemID (maps to SR_SolutionID) and F_CreatedDate, F_SubItemID (currently empty).
My goal is to identify which SolutionRevisions record was the active when a feedback item was created and insert the SR_ID value into F_SubItemID column. This could be done by choosing the revision record created most recently before the feedback item.
To begin, I've began by trying to select back appropriate values for testing and verification. What I have looks like this:
SELECT sr.SR_ID, f.F_ItemID, sr.SR_CreatedDateUtc, f.F_CreatedDateUtc
FROM Feedback AS f
INNER JOIN SolutionRevisions AS sr on f.F_ItemID = sr.SR_SolutionID
WHERE f.F_CreatedDateUtc > sr.SR_CreatedDateUtc
This is obviously missing a necessary portion of the where clause (thus returning inaccurate results). The where clause needs to include (in pseudo-code)
AND f.F_CreatedDateUtc < nextSRCreatedDate
^ where "nextSRCreatedDate" represents the sr.SR_CreatedDate of the next record on the SolutionRevisions table for the same SR_SolutionID. My issue lies in getting back the correct value for nextSRCreatedDate
Example data:
Any help is appreciated, if more info is requested I'll promptly reply.
Try this approach instead. It uses a subselect to determine the most recent record in the SolutionRevisions table at the time any individual Feedback record was created.
It's probably not the fastest solution (pun intended), but it should get you the desired results. If you're able to alter the subselect to a hit a better index, that would of course help with the execution time.
Update
f
Set
f.F_SubItemID = (
Select Top 1
sr.SR_ID
From
SolutionRevisions sr
Where
sr.SR_SolutionID = f.F_ItemID
And sr.SR_CreatedDateUtc < f.F_CreatedDateUtc
Order By
sr.SR_CreatedDateUtc Desc
)
From
Feedback f
My goal is to identify which SolutionRevisions record was the active when a feedback item was created and insert the SR_SolutionID value into F_SubItemID column.
I think you want outer apply:
SELECT sr.SR_ID, f.F_ItemID, sr.SR_CreatedDateUtc, f.F_CreatedDateUtc
FROM Feedback f OUTER APPLY
(SELECT sr.*
FROM SolutionRevisions sr
WHERE f.F_ItemID = sr.SR_SolutionID AND
f.F_CreatedDateUtc >= sr.SR_CreatedDateUtc
ORDER BY SR_CreatedDateUtc DESC
) sr;

sql-server-2008 : get the last status of subjects of a student

Salam, (Greetings) to all.
Intro:
I am working on a Student Examination System, where Students appear and pass or fail or absent.
Problem:
I am tasked to fetch their Summary of Status. you may say a Result Card which should print their very last status of a Subject.
Below is a sample of the data where a student has appeared many times, in different sessions. I have highlighted one subject in which a student has appeared three times.
Now, I write the following Query which extract the same result as the picture above:
SELECT DISTINCT
gr.STUDKEY,gr.SUBJECT_ID, gr.SUBJECT_DESC,gr.MARKS,
gr.PASSFAIL, gr.GRADE,max(gr.SESSION_ID), gr.LEVEL_ID
FROM RESULT gr
WHERE gr.STUDKEY = '0100106524'
GROUP BY gr.STUDKEY,gr.SUBJECT_ID, gr.SUBJECT_DESC,gr.MARKS,
gr.PASSFAIL, gr.GRADE, gr.LEVEL_ID
Desired:
I want to get only the last status of a subject in which a student has appeared.
Help is requested. Thanks in advanced.
Regards
I am using sql-server-2008.
This won't work because you include fields like gr.MARKS and gr.GRADE in the group by and in the select which means that the query might return more than 1 record for each session id while their grade or marks is different.
SELECT
gr.STUDKEY,gr.SUBJECT_ID, gr.SUBJECT_DESC,
gr.PASSFAIL, gr.GRADE,gr.SESSION_ID, gr.LEVEL_ID
FROM RESULT gr
JOIN (SELECT MAX(SessionId) as sessionId, STUDKEY
FROM RESULT
GROUP BY STUDKEY ) gr1 ON gr1.sessionId=gr.sessionid AND gr1.STUDKEY =gr.STUDKEY
Hopefully there is a date field, or something that indicates the order of the students appearances in this class. Use that to order your query in descending order, so that the most recent occurrence is the first record, then specifiy "Top 1" which will then give you only the most recent record for that student, which will include in his most recent status.
SELECT TOP 1
gr.STUDKEY,gr.SUBJECT_ID, gr.SUBJECT_DESC,gr.MARKS,
gr.PASSFAIL, gr.GRADE,gr.SESSION_ID, gr.LEVEL_ID
FROM RESULT gr
WHERE gr.STUDKEY = '0100106524'
ORDER BY gr.Date DESC //swap "Date" out for your field indicating the sequence.
or use a Group by with MAX(Date) if you're looking for multiple classes with the same student at the same time.

Access VBA: Get difference in value between current and previous record

I have made report based on query according to this link:
http://www.techonthenet.com/access/queries/max_query2.php
It gives me list of records with values:
(primaryKey)
ID.......FirstNum....SecNum.....Diameter.....Owner
1........100200.......01...............150..............Peter
2........100200.......02...............138..............Peter
3........100300.......07...............112..............John
Query sorts records in descending order by Diametral. I want make new column which will count difference between first and second record, then between third and second and so on. Like this:
(primaryKey)
ID.......FirstNum....SecNum.....Diameter.....DiffDiametral.....Owner
1........100200.......01...............150.......................................Peter
2........100200.......02...............138.............12......................Peter
3........100300.......07...............112.............26.....................John
What should I write into RowSource or DataSource for DiffDiametral to get these values? How can I avoid error for first line, where is not previous value which I want substract from?
I tried to solve it according to this link:
http://support.microsoft.com/kb/101081/en-us
but I did not solve it. Simply I dont know how I can refer previous value of Diameter to count difference.
Based on your information, a subquery should do it. Just substitute your actual table name for tblDiameters.
SELECT C.ID, C.FirstNum, C.SecNum, C.Diameter, C.Owner,
(SELECT TOP 1 P.Diameter
FROM tblDiameters AS P
WHERE P.Diameter < C.Diameter
ORDER BY P.Diameter DESC )
- C.Diameter AS DiffDiameter
FROM tblDiameters AS C

What does ORDER BY 5 DESC mean?

SELECT Departamentos.Nome_Dep,
Funcionarios.Nome AS Funcionario,
Funcionarios.Salario,
AVG(Funcionarios.Salario) OVER(PARTITION BY Departamentos.Nome_Dep) "Média por Departamento"
Salario - AVG(Funcionarios.Salario) OVER(PARTITION BY Departamentos.Nome_Dep) "Diferença de Salário" FROM Funcionarios
INNER JOIN Departamentos
ON Funcionarios.ID_Dep = Departamentos.ID
ORDER BY 5 DESC
The Order By 5 is throwing me off. I've never anything like it. Order By [colunmname] yes, but Order By [number], never seen before. I pulled this off an article.
Note: This is T-SQL.
Source: Window Functions in SQL Server 2005, 2008, 2012
This will order by the 5th field in this SELECT statement
Order by the 5th column in the result set.
The number represents the index of the column within your select list.
Source: http://mattberseth.com/blog/2007/05/quick_tip_order_by_1_descendin.html
Order by fifth column in the result set descending.
It is the SORTING BY RELATIVE POSITION.
You can use the SQL ORDER BY clause to sort by relative position in the result set, where the first field in the result set is 1. The next field is 2, and so on.
Here in this case Order by 5th field in the result set.
Go through http://www.techonthenet.com/sql/order_by.php
about sql order by.
Useful when a similar column name has become a calcuated output field,
In the following example, it would be confusing if say 'order by numberofVioation' as this column name has just become the name of a query output SUM field (of the same old column data)
So it become useful in calculated output field
Example:
Original fields:
name| Type| RiskLevel| Date| results| violations|
/* now add an extra Sum of Violation for each type, pls note 'order by 2 desc' refers to order by the 2nd queried column, ie hi to low */
select Type, sum(numberOfViolations) as numberOfViolations
from restaurantsTable
group by Type
order by 2 desc
Order by 5th field in the result set.