How do I select distinct values between two dates - c#

I am selecting two records between two dates, when doing this i am experiencing repeated record, I have used the word distinct but its not working: This is how my query looks:
public List<i> searchTwoDates(string firstDate, string secondDate)
{
DateTime fdate = Convert.ToDateTime(firstDate);
string realfirstDate = fdate.ToLongDateString();
DateTime sdate = Convert.ToDateTime(secondDate);
string realsecondDate = sdate.ToLongDateString();
List<i> date = new List<i>();
SqlConnection conn = new SqlConnection(....);
SqlCommand command = new SqlCommand(#"SELECT distinct * From TableName WHERE Cast(columnName AS DATE) > #columnName AND CAST(columnName AS DATE) < #columnName1 ORDER BY columnName1 Desc", conn);
command.Parameters.AddWithValue("#columnName", realfirstDate);
command.Parameters.AddWithValue("#columnName2", realsecondDate);
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Mod d = new Mod();
here i get my column names....
date.Add(d);
}
conn.Close();
return date;
}
I also have a unique ID in my database so we can use that to retrieve unique record but how would i write that?
Currently i am getting repeated records
ID FName sName Date
1 John JAck 2013-9-07
2 Linda Bush 2013-10-07
3 Linda Bush 2013-11-07
This is what i want
ID FName sName
1 John JAck 2013-9-07
2 Linda Bush 2013-11-07
This is the records between 2013-9-07 to 2013-11-07. in between these records i dont want any repeated ID

[migrated from comments]
You should use select distinct id, fname, sname from table. If you don't need the date, then this will work, no repetitions.

Try this
Select Max(ID),FName,sName,Max(Date)
FROM Table1
Where Date > 'SomeDate' And Date < 'SomeDate'
Group By FName,sName

Don't try using BETWEEN
SELECT DISTINCT ID,FName,sName,Date
FROM Table1
WHERE Date BETWEEN 'Date1' And 'Date2'
UPDATE
Because of the two different dates and IDs in the question above you should use grouping. This gives you:
SELECT MIN(ID),FName,sName, MIN(Date)
FROM Table1
WHERE Date BETWEEN 'Date1' And 'Date2'
ORDER BY ID
GROUP BY FName,sName
DISTINCT will not work as there are different IDs and dates for each record.
The above query will give you the first occuring ID. You can change the ORDER BY to Date to get the earliest. Or you want the most recent then use MAX instead of MIN and use ORDER BY with DESC.

Related

Select some of rows in C# database connection

I used database connection for connect to database and I selected some of rows in database table, like this code:
OleDbConnection objConnection = new OleDbConnection("server=localhost;database=sample;Data Source=|DataDirectory|\\sample.accdb");
objDataAdapter = new OleDbDataAdapter("SELECT description, category, account, price FROM SampleTable WHERE Select_ID = 12", objConnection);
now this code select 16 rows from SampleTable where Select_ID is 12 after that i need rows 3,5,7 how can i select this rows?
DataTable dt = new DataTable(); // get your data into this datatable
DataRow[] dr;
dr = dt.Select("WHERE Select_ID = 12");
if (dr.Length > 0)
{
//do something
}
You can use the ROW_NUMBER function. If you use it in the query you have, you will select by ROW_NUMBER of ALL rows. If I read correctly, you want rows 3,5,7 of the result set, so you would have to use a subquery:
SELECT * FROM (
SELECT description, category, account, price FROM SampleTable WHERE Select_ID = 12
) WHERE ROW_NUMBER() IN (3,5,7)
In the inner query, you are getting the 16-row result. The outer query now uses that result as a table/data source and selects the rows you need.
if order by column "id", then
SELECT t.description, t.category, t.account, t.price FROM (
SELECT ROW_NUMBER() OVER (ORDER BY id) as RowN, description, category, account, price FROM SampleTable WHERE Select_ID = 12
) as t WHERE RowN in (3,5,7)
else (ORDER BY id) change to your column
If your DataTable already contains those 16 rows but you want only row 3,5,7:
int[] indexes = { 2, 4, 6 };
dataTable1 = dataTable1.AsEnumerable()
.Where((row, index) => indexes.Contains(index))
.CopyToDataTable();
If you use a database that supports ranking functions you could use ROW_NUMBER. If you use SQL-Server >=2005 this works:
string sql = #"
WITH CTE AS
(
SELECT description, category, account, price,
rn = ROW_NUMBER() OVER (ORDER BY Select_ID, description, category, account, price)
FROM SampleTable
WHERE Select_ID = 12
)
SELECT description, category, account, price
FROM CTE
WHERE rn IN ( 3, 5, 7 );"

select latest 3 records from sql database

My table name is tblEvent and its columns are EventID, Name, Description, EventTypeID, TotalBudget, CustomerID, EventStatus, EventDate
I want to select the latest 3 records.
I have tried this:
public DataTable HomeEvents()
{
string query = "select TOP 3 tblEvent.*, tblCustomer.Name as 'CustomerName', tblCustomer.Photo AS 'CustomerPhoto' from tblEvent ORDER BY EventID DESC, tblCustomer where tblEvent.CustomerID = tblCustomer.CustomerID";
List<SqlParameter> lstParams = new List<SqlParameter>();
DataTable dt = DBUtility.SelectData(query, lstParams);
return dt;
}
The order by clause should be after the where clause:
select top 3
tblEvent.*,
tblCustomer.Name as 'CustomerName',
tblCustomer.Photo AS 'CustomerPhoto'
from
tblEvent
where
tblEvent.CustomerID = tblCustomer.CustomerID
order by
EventID desc,
tblCustomer
Note: If EventID is auto-incremented (primary key, identity) and the records are actually created in the order that they occured, then the field would be in increasing order over time. Otherwise you would need to use the EventDate field for sorting (as Tareq Alothman suggested).
As Guffa said, Order By comes after where, and you need to
"Order By EventDate DESC"
Change your SQL statement to read
... ORDER DESC BY ...
This will sort in reverse order, the first three are now the last three.

SQL comparison between 3 columns

I have 3 columns in my database. (1) Buy/Sell (2) ID (3) Date and time. For example:
buySel ID Date
1 234 12/12/2014
1 234 12/12/2014
2 234 12/12/2014
In buySell the number (1) is represented as buy and (2) is sell. Within the same day if the ID e.g. '234' is bought and sold this should return a error message.
This is what I have done in C#
string connectionString= "connection string goes here";
string Query = "SELECT COUNT(*) AS sum from databaseTable WHERE created_time >= DATEADD(hour, 9, CONVERT(DATETIME, CONVERT(DATE, GETDATE())))";
........
SqlDataReader data;
try
{
con.Open();
myReader = cmdg.ExecuteReader();
while (data.Read())
{
if (myReader[0].ToString() != "0")
{
MessageBox.Show("Error " + myReader[0].ToString());
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
I managed to compare it with today's date however how will I compare it to the buySell column and the ID column?
I'm not sure exactly what you want to return. The following will identify all the errors in your data, based on having a buy and sell in the same day:
select id, date
from databaseTable t
group by id, date
having sum(case when buysel = 1 then 1 else 0 end) > 0 and
sum(case when buysel = 2 then 1 else 0 end) > 0;
I'll like #GordonLinoff's answer, but haven't compared it performance wise to what you would get from a using EXISTS with correlated subqueries.
create table databaseTable (buySel TINYINT, ID INT, [Date] DATE)
insert into databaseTable values
(1,234,'12/12/2014'),
(1,234,'12/12/2014'),
(2,234,'12/12/2014')
select id
,[Date]
from databaseTable a
where exists(select 1 from databaseTable b where b.id=a.id
and b.[Date] = a.[Date]
and buysel = 1)
and exists(select 1 from databaseTable b where b.id=a.id
and b.[Date] = a.[Date]
and buysel = 2)
group by id
,[Date]
In this query the group by serves only as a more efficient DISTINCT.
EDIT:
Since the above statement has been questioned I figure I should examine it more closely. There a lot of discussion here and on the web at large. I think the sum of the guidance would be that GROUP BY is often more efficient then DISTINCT, but not always and DISTINCT is more intuitive a syntax.
Huge performance difference when using group by vs distinct
When the performance of Distinct and Group By are different?
http://msmvps.com/blogs/robfarley/archive/2007/03/24/group-by-v-distinct-group-by-wins.aspx

Sql query for two select statement

DateTime startDate = DateTime.ParseExact(txtstart.Text, "MM/dd/yyyy", null);
DateTime endDate = DateTime.ParseExact(txtend.Text, "MM/dd/yyyy", null);
string n1 = DropDownList2.SelectedItem.Text;
if (DropDownList1.SelectedItem.Text == "Membership")// here you can add selectedindex as well
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ToString());
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter("select * from Membership_det where updateDate between #Start and #End and FID ="+n1+"", con);
adapter.SelectCommand.Parameters.Add("#Start", SqlDbType.Date).Value = startDate;
adapter.SelectCommand.Parameters.Add("#End", SqlDbType.Date).Value = endDate;
}
……..
……..
Above is a part of a code to display the data in the grid view.I am displaying * from Membership_det and also need to display faculty name from other table…how to add the query with the above query..displaying * from membership _det table and faculty name from other table
FID MembNo MembType Validity Remarks UpdateDate
100 23 basn 6 dgag 9/5/2013 12:00:00 AM
200 566 basn 6 adhu 9/6/2013 12:00:00 AM
In this table i need to add Faculty name..it should be fetched from other table..
You can JOIN tables as below. Change the Relationship and the column names based on your tables. it is better if you can use parameter for FID as well
SELECT m.*, f.Name
FROM Membership_det m
INNER JOIN faculty f
ON m.FID = f.FID
WHERE m.updateDate between #Start and #End and m.FID =#FID ;
You can join Memberhip_det table with the other table to retrieve faculty_name. But these two tables should have a common connecting field or primary and foreign keys.
Also try using stored procedures rather than inline queries
Try to use union for your two sql select statements
UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.
Make foreign key relation ship to FID column on faculty table and change your query as follows
select Membership_det.MembNo, Membership_det.MembType,Membership_det.Validity,Membership_det.Remarks,Membership_det.UpdateDate,faculty.facultyname FROM Membership_det INNER JOIN faculty ON Membership_det.FID = faculty.FID
WHERE Membership_det.updateDate between #Start and #End and Membership_det.FID =#FID ;

Need to calculate number of rows in sql on the basis of modify date

What I'm trying to do is to calculate the number of rows of the table which updated 2 days means suppose I have some data like this:
ID Name Department DateTime ModifyDate
---------------------------------------------------------------------------
1 XXXXX IT 2013-09-10 09:53:01.000 2013-09-10 09:55:01.000
2 YYYYY Tech 2013-09-09 10:00:00.000 2013-09-10 12:00:00.000
3 WWWW IT 2013-09-09 08:09:00.000 2013-09-10 09:09:00.000
Now there are two rows which modify on 10 sep
I want a query which will give me the count of no. of row modify per day.
My desired out will be like this
No. of column
2
try this
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("Select count(ID) from TableName where ModifyDate>=#Today and ModifyDate<#NextDay", connection))
{
command.Parameters.Add(new SqlParameter("Today", DateTime.Today ));
command.Parameters.Add(new SqlParameter("Nextday", DateTime.Today.AddDays(1) ));
int count = 0;
int.TryParse( command.ExecuteScalar().ToString() , out count);
}
}
select Distinct Count(ID) from Table where ModifyDate between '2013-09-10' and '2013-09-11'
SELECT COUNT(ID) FROM TableX WHERE ModifyDate BETWEEN #FromDate and #ToDate;
Pass your start and end dates to the appropriate variables
You might want to use something like
SELECT count(ID)
FROM TableName
GROUP BY CAST(ModifyDate AS DATE)
SELECT CONVERT(DATE,ModifiedDate) AS DATE, count(ID) AS TotalUpdated
FROM TableName
GROUP BY CONVERT(DATE,ModifiedDate)
Try this query.
select count(*) as [No. of column] from Table1
where CAST(ModifyDate as Date) = 'Sep 10, 2013'
Replace 'Sep 10, 2013' with GetDate() if you want to filter on the current date.

Categories

Resources