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.
Related
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.
I have query like below , I tried to filter out duplicate columns by using Group BY
SELECT contacts.rowid AS ROW_PASS,
duty_rota.rowid AS ROW_PASS_ROTA,
duty_rota.duty_type AS DUTY_TYPE
FROM duty_rota,
duty_types,
contacts
WHERE duty_rota.duty_type = duty_types.duty_type
AND duty_rota.duty_officer = contacts.duty_id
AND sname IS NOT NULL
GROUP BY contacts.rowid,
duty_rota.rowid,
duty_rota.duty_type
ORDER BY duty_date
After playing with the query little bit I came to know we can't filter out distinct using group by while using ROWID. So can somebody please help me to write code (in SQL) with a logic that
if (any row is completely identical with another row of the query o/p)
{
then display only one column
}
I will be using the output as gridview's data source in C#, so if not in SQL - can you help me whether somehow in C# I can achieve to display only identical columns?
If you want to filter duplicate rows, you can use this query:
SELECT Max(duty_rota.rowid) AS ROW_PASS_ROTA,
duty_rota.duty_type AS DUTY_TYPE
FROM duty_rota,
duty_types,
contacts
WHERE duty_rota.duty_type = duty_types.duty_type
AND duty_rota.duty_officer = contacts.duty_id
AND sname IS NOT NULL
GROUP BY duty_rota.duty_type
ORDER BY DUTY_TYPE
Here you go: http://sqlfiddle.com/#!2/2a038/2
Take out the ROWID's. Example: If your table has 3 columns (colA, colB, colC) you could find exact row dups this way...
select a.* from
(
select count(*) dupCnt, colA, colB, colC from myTable
group by colA, colB, colC
) a
where dupCnt > 1
First, the ROWID is a unique field for each row, so using this field you will never have duplicates. The only solution here is to not use it. It's data does not hold anything you would want to display anyway.
Simply put, if you want no duplicates, you need the DISTINCT keyword:
SELECT DISTINCT field1,
field2
FROM table1,
table2
WHERE table1.key1 = table2.key1;
This will select all Field1, Field2 combinations from the two tables. Due to the DISTINCT keyword, each line will only be in the result list once. Duplicates will not be in the result list.
SELECT DISTINCT duty_rota.duty_type AS DUTY_TYPE
FROM duty_rota,
duty_types,
contacts
WHERE duty_rota.duty_type = duty_types.duty_type
AND duty_rota.duty_officer = contacts.duty_id
AND sname IS NOT NULL
ORDER BY duty_date
You will only need to GROUP BY if you need further operations on the result set, like counting the duplicates. If all you need is "no duplicates", the DISTINCT keyword is exactly what you are looking for.
Edit:
In case I misread your question and you want to see only those, that are duplicates, you need to group and you need to filter based on the groups criteria. You can do that using the HAVING clause. It's kind of an additional WHERE of the groups criteria:
SELECT FIELD1, FIELD2, COUNT(*)
FROM TABLE1, TABLE2
WHERE TABLE1.KEY1 = TABLE2.KEY1
GROUPB BY FIELD1, FIELD2
HAVING COUNT(*) > 1
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 ;
I have a table named emp with the following columns:
id int (autoincrement),
name varchar,
maxid int
I want to insert id, name, and maxid where maxid should be the value of autoincrement id.
Out of the two query options below, which one is best option and why?
option 1:
insert into emp (name,maxid) values ('abc',(select max(id)+1 from emp))
option 2:
string QRY = "insert into emp values('abc',0) select scope_identity()";
sqlcommand cmd= new sqlcommand(QRY, con);
datatable dt = new datatable();
con.open();
dt.load(cmd.executereader());
con.close();
int scopeid=int.parse(dt.rows[0][0].tostring());
QRY="update emp set maxid='"+scopeid+"' where id ='"+scopeid+"'";
cmd= new sqlcommand(QRY, con);
cmd.executenonquery();
easy way to do Demo is here
insert dbo.emp
select 'abc', IDENT_CURRENT('dbo.emp')
None of above are correct implementation of update.
But according to your scenario i would do two things.
First insert the names and use the auto increment to set the id and after that perform update no those records that do not have set yet the maxId.
Why do this in two stages ?
It is possible that we could have different result from MAX(id) and value of id set by incremental feature by database, so option 1 must be drop.
The query that could be used.
insert into emp (name) values ('abc')
update emp set maxid = id where maxid is null;
But from other hand and Serge observation, you should entirely drop this behavior if possible. Another alternative is to crate a trigger that kick after insert. Advantage of this is that above view or computed column is that you perform this operation only once.
I'll rather use INSERT INTO...SELECT statement,
INSERT INTO emp (name, maxid)
SELECT 'abc', COALESCE(MAX(id), 0) + 1
FROM emp
Select max(id)+1 could be different from autoincrement id so that option is not valid.
As for the second option it's still unnecessary complication. You can just insert with maxid NULL and then update to id
insert into emp (name,maxid) values ('abc',NULL)
update emp set maxid = id where maxid is null
How can i merge two Datatables into the same row. I am using different stored procedures to get data into datasets. In asp.net using c#, i want to merge them so there are same number of rows as table 1 with an added column from table 2.
For example:
DataTable table1 = dsnew.Tables[0];
DataTable table2 = dsSpotsLeft.Tables[0];
table1.Merge(table2);
This is fetching me 4 rows instead of 2 rows. What am i missing here? Thanks in advance!!
You cannot use the method Merge in this case, instead you should create new DataTable dt3, and then add columns and rows based on the table 1 and 2:
var dt3 = new DataTable();
var columns = dt1.Columns.Cast<DataColumn>()
.Concat(dt2.Columns.Cast<DataColumn>());
foreach (var column in columns)
{
dt3.Columns.Add(column.ColumnName, column.DataType);
}
//TODO Check if dt2 has more rows than dt1...
for (int i = 0; i < dt1.Rows.Count; i++)
{
var row = dt3.NewRow();
row.ItemArray = dt1.Rows[i].ItemArray
.Concat(dt2.Rows[i].ItemArray).ToArray();
dt3.Rows.Add(row);
}
Without knowing more about the design of these tables, some of this is speculation.
What it sounds like you want to perform is a JOIN. For example, if you have one table that looks like:
StateId, StateName
and another table that looks like
EmployeeId, EmployeeName, StateId
and you want to end up with a result set that looks like
EmployeeId, EmployeeName, StateId, StateName
You would perform the following query:
SELECT Employee.EmployeeId, Employee.EmployeeName, Employee.StateId, State.StateName
FROM Employee
INNER JOIN State ON Employee.StateId = State.StateId
This gives you a resultset but doesn't update any data. Again, speculating on your dataset, I'm assuming that your version of the Employee table might look like the resultset:
EmployeeId, EmployeeName, StateId, StateName
but with StateName in need of being populated. In this case, you could write the query:
UPDATE Employee
SET Employee.StateName = State.StateName
FROM Employee
INNER JOIN State ON Employee.StateId = State.StateId
Tested in SQL Server.
Assuming you have table Category and Product related by CategoryID, then try this
var joined = from p in prod.AsEnumerable()
join c in categ.AsEnumerable()
on p["categid"] equals c["categid"]
select new
{
ProductName = p["prodname"],
Category = c["name"]
};
var myjoined = joined.ToList();
Sources
LINQ query on a DataTable
Inner join of DataTables in C#
http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataset/thread/ecb6a83d-b9b0-4e64-8107-1ca8757fe58c/
That was a LINQ solution. You can also loop through the first datatable and add columns from the second datatable