How to get the following output using SQL SERVER 2008 - sql-server

I need to implement a logic where I need to get the latest group data from a table .
Here is the example.
Result Date
PASS 6/1/2016
PASS 6/2/2016
FAIL 6/10/2016
FAIL 6/11/2016
PASS 6/20/2016
PASS 6/21/2016
FAIL 7/1/2016
FAIL 7/5/2016
PASS 7/10/2016
PASS 7/11/2016
Required output
ID Result Date
PASS 7/10/2016
PASS 7/11/2016
Can you please help me?

SELECT
ID,
RESULT,
MAX(Date) as Date
FROM Table
GROUP BY ID, RESULT
The solution returns a single row for each ID and RESULT combination as noted by the GROUP BY clause. The row that is returned is the one which has the MAX date, aka the most current date even if it's in the future, with this pairing or grouping.

SELECT * FROM *table_name* WHERE ID IN (9, 10)

Related

SQL Server: Slowly Changing Dimension Type 2 on historical records

I am trying to set up a SCD of Type 2 for historical records within my Customer table. Attached is how the Customer table is set up alongside the expected outcome. Note that the Customer table in practice has 2 million distinct Customer IDs. I tried to use the query below, but the Start_Date and End_Date are repeating for each row.
SELECT t.Customer_ID, t.Lifecyle_ID, t.Date As Start_Date,
LEAD(t.Date) OVER (ORDER BY t.Date) AS End_Date
FROM Customer AS t
I think a three step query is likely needed.
Use LEAD and LAG, partitioned by Customer and ordered by date, to peek at the next row's values for both Date and Lifecycle.
Use a CASE statement to emit a value for End Date when the current row's Lifecycle <> the next row's lifecycle (otherwise emit NULL). Now do the same using LAG for the Effective Date.
Group By or Distinct on the output from Step #2.
Hopefully that makes sense. I'll try to post a code example later today, but hopefully that's enough to get you started.

how to select first rows distinct by a column name in a sub-query in sql-server?

Actually I am building a Skype like tool wherein I have to show last 10 distinct users who have logged in my web application.
I have maintained a table in sql-server where there is one field called last_active_time. So, my requirement is to sort the table by last_active_time and show all the columns of last 10 distinct users.
There is another field called WWID which uniquely identifies a user.
I am able to find the distinct WWID but not able to select the all the columns of those rows.
I am using below query for finding the distinct wwid :
select distinct(wwid) from(select top 100 * from dbo.rvpvisitors where last_active_time!='' order by last_active_time DESC) as newView;
But how do I find those distinct rows. I want to show how much time they are away fromm web apps using the diff between curr time and last active time.
I am new to sql, may be the question is naive, but struggling to get it right.
If you are using proper data types for your columns you won't need a subquery to get that result, the following query should do the trick
SELECT TOP 10
[wwid]
,MAX([last_active_time]) AS [last_active_time]
FROM [dbo].[rvpvisitors]
WHERE
[last_active_time] != ''
GROUP BY
[wwid]
ORDER BY
[last_active_time] DESC
If the column [last_active_time] is of type varchar/nvarchar (which probably is the case since you check for empty strings in the WHERE statement) you might need to use CAST or CONVERT to treat it as an actual date, and be able to use function like MIN/MAX on it.
In general I would suggest you to use proper data types for your column, if you have dates or timestamps data use the "date" or "datetime2" data types
Edit:
The query aggregates the data based on the column [wwid], and for each returns the maximum [last_active_time].
The result is then sorted and filtered.
In order to add more columns "as-is" (without aggregating them) just add them in the SELECT and GROUP BY sections.
If you need more aggregated columns add them in the SELECT with the appropriate aggregation function (MIN/MAX/SUM/etc)
I suggest you have a look at GROUP BY on W3
To know more about the "execution order" of the instruction you can have a look here
You can solve problem like this by rank ordering the results by a key and finding the last x of those items, this removes duplicates while preserving the key order.
;
WITH RankOrdered AS
(
SELECT
*,
wwidRank = ROW_NUMBER() OVER (PARTITION BY wwid ORDER BY last_active_time DESC )
FROM
dbo.rvpvisitors
where
last_active_time!=''
)
SELECT TOP(10) * FROM RankOrdered WHERE wwidRank = 1
If my understanding is right, below query will give the desired output.
You can have conditions according to your need.
select top 10 distinct wwid from dbo.rvpvisitors order by last_active_time desc

Without updating the column values in Oracle , is there a way to store the data in a variable and get a count on those data using where condition?

I am new to Oracle. I need some help in this. So the scenario is that without updating any column value in the table I have to store a DATE value and from that DATE value I have to get a count based on a where condition, which i know we will use a '<=' operator.
For Example,lets say i have a column "Sweep_Date", in this column,for the time being all the values are nulll.
I am having nearly 2,92,300 rows in which I have to update the date values. But without updating the Sweep_Date column, Is there any way that i can store some dates in the column, for which i can write a where condition and get the count(*) from the table based upon the WHERE condition applied??
Can we use a temp Variable??
Any help is appreciated......
Aha, I think I got it.
If sweep_date is empty and you can't/won't update it, then use NVL function. For example:
select count(*)
from your_table t
where nvl(t.sweep_date, date '2020-04-28') > t.some_other_date;
If you use date column from another table, then join tables and use another table's column in NVL. For example:
select count(*)
from your_table t join another_table j on j.some_id = t.some_id
where nvl(t.sweep_date, j.some_date) > t.some_other_date;

Current date being returned multiple times?

I've got a simple query which works as expected the first time.
However, when I re-run it, it returns the same result 504 times, instead of once.
Does anyone know why this would happen?
SELECT GETDATE(), CAST (GETDATE() AS DATE) AS Casted_Date
from Production.Product
The count of rows based on your count of rows in Production.Product table.
This query is not valid anymore to validate since you are casting Date datatype as Date again.

SQL Get Second Record

I am looking to retrieve only the second (duplicate) record from a data set. For example in the following picture:
Inside the UnitID column there is two separate records for 105. I only want the returned data set to return the second 105 record. Additionally, I want this query to return the second record for all duplicates, not just 105.
I have tried everything I can think of, albeit I am not that experience, and I cannot figure it out. Any help would be greatly appreciated.
You need to use GROUP BY for this.
Here's an example: (I can't read your first column name, so I'm calling it JobUnitK
SELECT MAX(JobUnitK), Unit
FROM JobUnits
WHERE DispatchDate = 'oct 4, 2015'
GROUP BY Unit
HAVING COUNT(*) > 1
I'm assuming JobUnitK is your ordering/id field. If it's not, just replace MAX(JobUnitK) with MAX(FieldIOrderWith).
Use RANK function. Rank the rows OVER PARTITION BY UnitId and pick the rows with rank 2 .
For reference -
https://msdn.microsoft.com/en-IN/library/ms176102.aspx
Assuming SQL Server 2005 and up, you can use the Row_Number windowing function:
WITH DupeCalc AS (
SELECT
DupID = Row_Number() OVER (PARTITION BY UnitID, ORDER BY JobUnitKeyID),
*
FROM JobUnits
WHERE DispatchDate = '20151004'
ORDER BY UnitID Desc
)
SELECT *
FROM DupeCalc
WHERE DupID >= 2
;
This is better than a solution that uses Max(JobUnitKeyID) for multiple reasons:
There could be more than one duplicate, in which case using Min(JobUnitKeyID) in conjunction with UnitID to join back on the UnitID where the JobUnitKeyID <> MinJobUnitKeyID` is required.
Except, using Min or Max requires you to join back to the same data (which will be inherently slower).
If the ordering key you use turns out to be non-unique, you won't be able to pull the right number of rows with either one.
If the ordering key consists of multiple columns, the query using Min or Max explodes in complexity.

Resources