SQL query to get the sum and the latest enries - c#

I have a table called machineStatus:
ID Successfiles totaldata Backupsessiontime
> 1 3 988 1256637314
> 2 21 323 1256551419
> 3 8 23 1256642968
> 4 94 424 1256642968
> 1 42 324 1256810937
> 1 0 433 1256642968
Now here i want to group by ID where the successfiles and total data gets summed up, but only display the latest Backupsessiontime.
I can do this seperately but not together.
Any suggestions????
For doing this seperately:
to get the sum:
select ID, sum(NumOfSuccessFiles), sum(TotalData)
from MachineStat
group by ID;
to get latest:
With idT as (
select ID
from MachineStat
group by ID
)
select applyT.*
from idT p
CROSS APPLY (
select top 1 ID,BackupSessionTime from MachineStat where eID=p.ID
order by MachineID desc
) as applyT

It looks like you want to do
select ID, sum(NumOfSuccessFiles), sum(TotalData), max(Backupsessiontime)
from MachineStat
group by ID;

You can use an aggregate function that would suit your needs:
select
ID,
sum(NumOfSuccessFiles) TotalNumOfSuccessFiles,
sum(TotalData) TotalData,
max(Backupsessiontime) LastBackupsessiontime
from
MachineStat ms
group by
ID
Or you can use a sub-query in your primary query, if you need more complicated sorting logic.
select
ID,
sum(NumOfSuccessFiles) TotalNumOfSuccessFiles,
sum(TotalData) TotalData,
(select top 1 Backupsessiontime from MachineStat where ID = ms.ID order by ...) LastBackupsessiontime
from
MachineStat ms
group by
ID

Max(BackupSessionTime) ?

Related

GROUP BY, ORDER BY and taking first in LINQ

Suppose I have a table with two columns:
TABLE A
-------
ProjectID NUMBER
STATUS VARCHAR2(6) // either 'CLOSED' or 'NEW'
There could be maximum two entries for a ProjectID with the two possible values of STATUS and the combination (ProjectID, STATUS) is unique.
I need to select only those ProjectID's that have status 'NEW'. Also, if for a projectID, there are two entries with different statuses (NEW and CLOSED), I don't want it in the output.
I tried using group by, then ordering the resultset descending (so as to get 'NEW' row for a project ID first) and then taking the first row in LINQ, similar to this:
var query = (from a in context.A.Where(o => o.STATUS == 'NEW')
group a by a.ProjectID into groups
select groups.OrderByDescending(o => o.ProjectID)
.ThenBy(o => o.STATUS)
.FirstOrDefault());
Butt it's resulting into an "APPLY" clouse in the query which is resulting into an error. Apparantly, Oracle 10g doesn't support it.
Any help is appreciated.
Something like this, perhaps?
SQL> with test (projectid, status) as
2 (select 1, 'new' from dual union -- should be returned
3 select 2, 'new' from dual union
4 select 2, 'closed' from dual union
5 select 3, 'closed' from dual union
6 select 4, 'new' from dual -- should be returned
7 )
8 select projectid
9 from test
10 group by projectid
11 having min(status) = max(status)
12 and min(status) = 'new';
PROJECTID
----------
1
4
SQL>
Proper tu use having count(distinct STATUS=1) :
create table tableA( ProjectID int, STATUS varchar2(10) );
insert all
into tableA values(1 ,'NEW')
into tableA values(1 ,'CHANGED')
into tableA values(2 ,'NEW')
into tableA values(3 ,'CHANGED')
select * from dual;
/
select * from
(
select ProjectID, max(STATUS) STATUS
from tableA
group by ProjectID
having count(distinct STATUS)=1
)
where STATUS = 'NEW';
I believe I have accomplished what you want, using a subquery in LINQ.
var query = (from a in context.A
where (from b in context.A
where b.ProjectID == a.ProjectID
select new { a.ProjectID, a.STATUS }).Distinct().Count() == 0
&& a.STATUS == "NEW"
select a.ProjectID).ToList();
Essentially, the outer query just makes sure that each a record has a NEW status, and the inner query makes sure that there are no two distinct records with the given ProjectID, because if there are, one is CLOSED. I avoided using a GROUP BY since you said your database does not support LINQ's way of doing it.
I hope I understood your problem correctly, and I hope this helps!

Fetch alternate series of records in SQL Server

I want to get alternate series of records using SQL Server.
For example :
I want to skip first 10 records (1 to 10) in sequence and get other 10 records (11 to 20) after that I want to skip next 10 records (21 to 30) and get another next 10 records (31 to 40)
I have done for alternate rows as below...
SELECT ROW, EmployeeID
FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY EmployeeID) AS ROW, *
FROM Employee) A
WHERE
ROW % 2 = 0
But in case of my requirement above logic will not work. Please help me to make above thing works..
Linq will also accepted
Thanks
SELECT ROW, EmployeeID
FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY EmployeeID) AS ROW, *
FROM Employee) A
WHERE
((ROW - 1)/10) % 2 = 1
I have done above of your requirement like below (Example).
Generated 1200 number sequentially from 1 to 1200 like below
;WITH CTE
AS
(
SELECT 1 PERIOD_SID
UNION ALL
SELECT PERIOD_SID+1 FROM CTE WHERE PERIOD_SID<1200
)
SELECT * INTO #PERIOD1 FROM CTE
OPTION(MAXRECURSION 0)
After this i have find alternative numbers like you have mentioned in your query
SELECT PERIOD_SID FROM
(
SELECT CASE
WHEN PERIOD_SID%10 <> 0 THEN PERIOD_SID / 10
WHEN PERIOD_SID%10 = 0 THEN ( PERIOD_SID / 10 ) - 1
END RNO,
PERIOD_SID
FROM #PERIOD1 )A
WHERE RNO%2=0
so if you have sequential numbers in your query (If you dont have generate using rownumber) then apply above logic.
Your query need to convert like below.
SELECT EMPLOYEEID
FROM (SELECT Row_number()
OVER (
ORDER BY EMPLOYEEID)AS ROW,
*
FROM EMPLOYEE) A
WHERE ( CASE
WHEN RNO%10 <> 0 THEN RNO / 10
WHEN RNO%10 = 0 THEN ( RNO / 10 ) - 1
END )%2 = 0
may be you can try this
SELECT ROW, EmployeeID FROM(
SELECT ROW_NUMBER()OVER (ORDER BY EmployeeID)AS ROW,* FROM Employee)
A WHERE ((ROW - (ROW%10))/10) % 2 = 1
Don't if this works or not coz I dont have sql server to run. Please show the error/result after running this query.
Ask if any doubt.

Monthly Report - SQL

I have the table below, how would I select in SQL the last date of each month (from the list) in each categoryID?
I want to end up with something in the line off:
CategoryID | Current | Date
1 | 5 | 2016-09-30
1 | 3 | 2016-10-30
1 | 7 | 2016-11-30
1 | 2 | 2016-12-30
etc. as history builds up.
Image :
There are a few ways to approaches to do this, one of them could be using windowing function rownumber. Within the CTE (WITH) you get local order of the records within date(using covert to get rid of the time here)+CategoryID partition by datetime DESC (-> first is latest). You need to do this because you cannot use windowing functions in WHERE clause. Then, in the main query, you actually use this CTE as your source table and get only the latest record per partition.
WITH LocallyOrdered AS (
SELECT CategoryID,
StockCurrent,
ROW_NUMBER() OVER (
PARTITION BY CategoryID, CONVERT(date, RecordAdded)
ORDER BY RecordAdded DESC)
AS RowNumberOneIsLatest
FROM OriginalTable)
SELECT CategoryID, StockCurrent FROM LocallyOrdered WHERE RowNumberOneIsLatest = 1
Considering you're using MySQL, since you haven't mentioned.
Suppose this is your table named : 'Dummy'
cat_id current date
------ ------- --------
1 5 2016-09-30
1 3 2016-10-30
1 7 2016-11-30
1 2 2016-12-30
2 4 2016-10-31
2 6 2016-10-04
Executing this query :
select
o.cat_id,
(SELECT DISTINCT
a.date
from
Dummy a
where a.cat_id = o.cat_id
ORDER BY date DESC
LIMIT 1) as 'date'
from
Dummy o
group by o.cat_id ;
Gives you the Latest date of each category :
cat_id date
------ ------------
1 2016-12-30
2 2016-10-31
EDIT
This is supposed to work specifically for your table. Just replace "yourTable" with the table's actual name.
select
o.CategoryID,
o.StockCurrent
(SELECT DISTINCT
a.RecordAdded
from
yourTable a
where a.CategoryID = o.CategoryID
ORDER BY RecordAdded DESC
LIMIT 1) as 'RecordAdded'
from
yourTable o
group by o.CategoryID ;
EDIT 2 :
This Query returns the latest date of each month within a certain category. Hope this is what you want.
SELECT
o.CategoryID,
o.StockCurrent,
o.RecordAdded
FROM
`yourTable` o
WHERE o.RecordAdded IN
(SELECT
MAX(i.RecordAdded)
FROM
`yourTable` i
GROUP BY MONTH(i.RecordAdded))
GROUP BY o.CategoryID,
o.RecordAdded ;
Suppose the table contains the following sample data:
CategoryID StockCurrent RecordAdded
---------- ------------ -------------
1 5 2016-09-01
1 3 2016-09-02
1 7 2016-10-01
1 2 2016-10-02
2 4 2016-09-01
2 6 2016-09-02
2 66 2016-10-01
2 77 2016-10-02
Running this query returns the following result set :
CategoryID StockCurrent RecordAdded
---------- ------------ -------------
1 3 2016-09-02
1 2 2016-10-02
2 6 2016-09-02
2 77 2016-10-02
try this:
WITH Temp As
(
select CategoryId, [Current], RecordAdded,
Dense_Rank() over( partition by CategoryId order by RecordAdded desc) as CatergoryWiseRank
from tblCategory
)
select CategoryId, [Current], RecordAdded from Temp where CatergoryWiseRank=1
SELECT
CASE MONTH(date_field)
WHEN 1 THEN 'Enero'
WHEN 2 THEN 'Febrero'
WHEN 3 THEN 'Marzo'
WHEN 4 THEN 'Abril'
WHEN 5 THEN 'Mayo'
WHEN 6 THEN 'Junio'
WHEN 7 THEN 'Julio'
WHEN 8 THEN 'Agosto'
WHEN 9 THEN 'Septiembre'
WHEN 10 THEN 'Octubre'
WHEN 11 THEN 'Noviembre'
WHEN 12 THEN 'Diciembre'
END as Mes, COUNT(date_field) as cantidad FROM nacimientos
WHERE YEAR(date_field)='1991'
GROUP BY MONTH(date_field)asc
Result

How to select multiple Row and multiple field by one code with SQL

I want to select multiple row on a table. But I want to select fields every row too. Here is sample table :
---------------------
OrNo | Name | value
---------------------
1154 | Michael | 41
1154 | Rico | 24
1487 | Alex | 21
1487 | Leo | 27
I want to select based where "Orno" code which in the table is multiple. so I want to get every name and value on 1 of "OrNO".
For an example, I want to select where OrNO 1154. How to select all of name and value from that code? How to used sql data reader for read them?
Edit:
Based answered, I'm sorry, I want to execute on behind code, like sqldatareader with C#/VB.Net. I dont know how to execute them on behind code to store to varriable.
Thank you
SELECT *
FROM MyTable
WHERE OrNo IN
(
SELECT OrNo
FROM
(
SELECT OrNo, COUNT(*) AS RecordCount
FROM MyTable
GROUP BY OrNo
) A
WHERE RecordCount > 1
)
You want to return duplicate records per OrNo, so count per OrNo and only return records with a count > 1.
select orno, name, value
from
(
select orno, name, value, count(*) over (partition by orno) as cnt
from mytable
)
where cnt > 1
order by orno;
It's hard to understand your question.
Are you searching for the SQL Statement? If so, I would suggest:
SELECT *
FROM <TABLE_NAME>
WHERE OrNo IN
(
SELECT OrNo
FROM <TABLE_NAME>
GROUP BY OrNo
HAVING COUNT(*) > 1
)
Sorry, #jmcilhinney was faster here.
And one more, with ties
with t as (
select * from (values
(1154,'Michael',41),
(1154,'Rico',24),
(1199,'Mary',25),
(1487,'Alex',21),
(1487,'Leo',27)) t(OrNo, Name, value )
)
select top(1) with ties OrNo, Name, value
from t
order by
case count(*) over (partition by OrNo ) when 1 then 1 else 0 end

selecting last record from table

I am deveoping a c# app in which oledb connection is used.
My table is following
payment
Id RemFee
1 2000
2 2500
1 1500
3 8000
3 5000
2 500
3 0
I want to select and check only last record of each Id and compare Remfee to 0. If it is greater than 0 then print the record. i.e. My expected result is:
Id
1
2
In this check is made for Id 1 with RemFee 1500 (as it is last record with Id1). It is grater than 0 hence record is printed.
Guessing you are using MSQ SQL Server and no row to know wich is your last inserted row. Try this code:
SELECT Id, Min(RemFee) AS RemFee
FROM payment
WHERE RemFee > 0
GROUP BY ID
Here is an SQL Fiddle working code sample
EDIT
If you only want the ID field here is one option, together with the SQL Fiddle code
SELECT myTable.Id
FROM (SELECT Id as ID, Min(RemFee) AS Remfee
FROM payment
WHERE RemFee > 0
GROUP BY ID
) myTable
SELECT ID,MIN(REMFEE) FROM payment WHERE ID NOT IN (SELECT ID FROM payment WHERE REMFEE = 0) GROUP BY ID
Select
id, Min(RemFee)
from payment
where RemFee > 0
group by id

Categories