How to use order by on the basis of 3 condtiton - asp.net

I am working on an application in asp.net window application whose data stored in excel sheet.
I have a sheet in excel:
Sheet2(STATE,Point)
on the basis of points the each state gets medals which has following criteria:-
Gold : 7 points
Silver : 5 Points
Bronze : 4 Points
I want total medal of each STATE on the basis of their medals type means the STATE having most gold medal should be top.If 2 STATE have same number of Gold then the STATE having more silver medals should be on higher position.And if 2 STATE have same number of silver medals then the STATE having more Bronze medals should be on higher position. I have done following query:-
OdbcConnection con = new OdbcConnection(ConfigurationManager.ConnectionStrings["SportTech"].ConnectionString);
//string query = "select STATE,sum(Point) as MEDAL from [Sheet2$] Group by STATE order by sum(Point) desc";
//string query = "SELECT STATE,SUM(Point) AS MEDAL,(CASE Point == 7: 1 END) AS GoldCount FROM [Sheet2$] GROUP BY STATE ORDER BY SUM(Point) DESC";
string query = "select STATE,sum(Point) as MEDAL, sum(IIF(point = 7,1,0)) as Gold, sum(IIF(point = 5,1,0)) as Silver, sum(IIF(point = 4,1,0)) as Bronce from [Sheet2$] group by STATE order by sum(IIF(point = 7,1,0)) desc";
OdbcCommand cmd = new OdbcCommand(query, con);
OdbcDataAdapter da = new OdbcDataAdapter(cmd);
con.Open();
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
but the query is not working if 2 STATE having similar Gold or Silver medals.kindly help me..Thanx

Assuming your calculations for the medals works, you should be able to simply add the extra arguments to the ORDER BY clause as so:
string query = "select STATE,sum(Point) as MEDAL, sum(IIF(point = 7,1,0)) as Gold, sum(IIF(point = 5,1,0)) as Silver, sum(IIF(point = 4,1,0)) as Bronce from [Sheet2$] group by STATE order by sum(IIF(point = 7,1,0)) desc, sum(IIF(point = 5,1,0)) desc, sum(IIF(point = 4,1,0)) desc";

Related

Retrieve id with condition

I am trying to allocate academy for student with only one click. This allocation need to have condition before allocating a specific academy to the student.
Here are my database tables:
tblAcademy
Acad_id name seat_available
------------------------------
1 A 2
2 B 2
3 C 1
4 D 5
5 E 3
tblStudent
stud_Id name `stud_purcentage` `stud_result` acad_id
----------------------------------------------------------
1 Alex 100 `Pass`
2 Lee 80.5 `Pass`
3 Lea 40.3 `Fail`
4 Loane 10 `Fail`
5 john 50 `Pass`
tblAcademy_selection
stud_id Acad_id order_preference
--------------------------------
1 1 1
1 3 2
4 3 1
4 2 2
4 4 3
Acad_id is foreign key of tblAcademy. The acad_id can remain null if the condition is not respected a student may do not have academy.
In the tblAcademy selection it shows that a student can select many academy but only one has to be allocate to them.
The allocation must be based on the seat available by the academy, on those who pass and allocate those from best percentage to the worst.
Till now I have been able to retrieve from the best to worst student and those who passed. I have then join those student id to the tblAcademy_selection.
SqlConnection dbcon = new SqlConnection(_conString);
SqlCommand scmd = new SqlCommand();
scmd.CommandText = "SELECT stud_Id, stud_fname, stud_purcentage, stud_totalMarks FROM tblStudent WHERE stud_result = 'Pass' ORDER BY stud_purcentage DESC";
scmd.Connection = dbcon;
SqlDataAdapter da = new SqlDataAdapter(scmd);
DataTable dt = new DataTable();
dbcon.Open();
da.Fill(dt);
string[] array = new string[dt.Rows.Count];
// foreach (DataRow row in dt.Rows)
for (int a = 0; a < dt.Rows.Count; a++)
{
// studID = row["stud_Id"].ToString();
array[a] = dt.Rows[a]["stud_Id"].ToString();
SqlCommand scmd2 = new SqlCommand();
scmd2.CommandText = "SELECT * FROM tblAcademy ta JOIN tblAcademy_Selection tas ON ta.acad_Id = tas.acad_Id WHERE stud_Id IN ('" + array[a] + "')";
scmd2.Connection = dbcon;
SqlDataAdapter da2 = new SqlDataAdapter(scmd2);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
string[] array2 = new string[dt2.Rows.Count];
for (int a2 = 0; a2 < dt2.Rows.Count; a2++)
{
array2[a2] = dt2.Rows[a2]["stud_Id"].ToString();
SqlCommand scmd3 = new SqlCommand();
}
}
In my first SQL statement I have selected those who have best percentage and those whose who passed and stored in an array.
With the for loop I am retrieving the data table value
In the second SQL statement, I have made a join with tblAcademy and tblAcademy_selection where the tblAcademy_selection.stud_id is in the retrieve value that I have done in the first statement.
I am having difficulty to apply the condition in which if an student choice of academy seat is full it move to the second choice and if the second is full it move to the third and so on.
A student may not have academy if all his choice academy seat is full.
You have to apply a filter condition in your SQL statement to filter out records with tblAcademy.seat_available = 0.
Then generate a row_number or rank based on order preference and retrieve records with generated row_number =1.
Something like this:
SELECT * FROM
(
SELECT tas.*, DENSE_RANK() OVER (PARTITION BY stud_id ORDER BY order_preference) AS row_id
FROM tblAcademy ta
JOIN tblAcademy_Selection tas ON ta.acad_Id = tas.acad_Id
WHERE ta.seat_available >0 and stud_Id IN ('" + array[a] + "')"
) DTL
WHERE row_id = 1

Store multiple items in a single table column in SQL Server database

Currently I have
public void bindgrid()
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlCommand cmd = new SqlCommand("select p.[name], cd.CustomerName, cd.CustomerEmailID,cd.CustomerPhoneNo,cd.CustomerAddress,cd.TotalPrice,cd.OrderDateTime, cd.PaymentMethod FROM CustomerDetails cd Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id Inner Join Products p ON cp.ProductID = p.ProductID", conn);
SqlDataAdapter da = new SqlDataAdapter("", conn);
da.SelectCommand = new SqlCommand("select p.[name], cd.CustomerName, cd.CustomerEmailID,cd.CustomerPhoneNo,cd.CustomerAddress,cd.TotalPrice,cd.OrderDateTime, cd.PaymentMethod FROM CustomerDetails cd Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id Inner Join Products p ON cp.ProductID = p.ProductID", conn);
DataSet ds = new DataSet();
da.Fill(ds, "data");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
and the result:
What I want to happen is that since it is in the same ID (10), would it be possible if I can have multiple values inside my Name column? like lpg, oxygen, etc?
Update: so far I got
this
I just want to store multiple values in my name column to avoid redundancy. please help
Separate your transactions from the items into two separate tables. Use the transaction ID as a foreign key in the items-purchased table. That is:
Remove the column name from your existing table
Create a new table with name and Id
Insert just one row into your existing table with a unique Id
Insert multiple rows into the new table with the same Id and the various names
So your second table would contain rows:
Id name
...
10 Carbon Dioxide
10 Industrial Oxygen
11 (a different purchase)
11 (a different purchase)
...

How to Count total Medal of Sports data from excel

I am working on a window application in ASP.NET. To store the data I am using an Excel sheet. The Excel sheet has following fields:
STATE
Point
For getting I have following criteria:
Gold - 7 Point
Silver- 5 Points
Bronze- 4 Points
I want to count total number gold, silver and bronze medal obtained by each State. For this I used following query:
OdbcConnection con = new OdbcConnection(ConfigurationManager.ConnectionStrings["SportTech"].ConnectionString);
//string query = "select STATE,sum(Point) as MEDAL from [Sheet2$] Group by STATE order by sum(Point) desc";
string query = "SELECT STATE,SUM(Point) AS MEDAL,SUM(CASE WHEN Point = 7 THEN 1 ELSE 0 END) AS GoldCount,SUM(CASE WHEN Point = 5 THEN 1 ELSE 0 END) AS SilverCount,SUM(CASE WHEN Point = 4 THEN 1 ELSE 0 END) AS BronzeCount FROM [Sheet2$] GROUP BY STATE ORDER BY SUM(Point) DESC";
OdbcCommand cmd = new OdbcCommand(query, con);
OdbcDataAdapter da = new OdbcDataAdapter(cmd);
con.Open();
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
But it is showing the error:
ERROR [42000Օ] [Microsoft][ODBC Excel Driver] Syntax error (missing
operator) in query expression 'SUM(CASE WHEN Point = 7 THEN 1 ELSE 0
END)'.
How can I resolve this error?
Thanks!
If I understood correctly you could try this. I'm using OleDB instead of Odbc
string constring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\\statetest.xls;Extended Properties=\"Excel 8.0;HDR=YES\"";
OleDbConnection con = new OleDbConnection(constring);
string query = "select STATE,sum(IIF(point = 7,1,sum(IIF(point = 5,1,sum(IIF(point = 4,1,0)))))) as PointsPerState,sum(IIF(point = 7,1,0)) as Gold, sum(IIF(point = 5,1,0)) as Silver, sum(IIF(point = 4,1,0)) as Bronce from [Sheet2$] group by STATE";
OleDbCommand cmd = new OleDbCommand(query, con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
con.Open();
DataTable dt = new DataTable();
da.Fill(dt);

Is it possible to have asp:calender show a date from the database?

I am trying to have a user type a year into a textbox and if the year exits in the database (which has specific dates for semesters) it displays these dates in a calender.
I have looked for a few days for how to do this but I'm not able to find anything of help.
Is this even possible? I was hoping to be able to use a SQLDataSource for this but I can't add a connection string to a calender.
Any help would be great!
Mark
*REVISED****
I have a table in my database where it has the start date and end date of each university semester year, e.g. autumn, spring, summer and also the Easter holidays. I want the user to be able to type the year they wish to change the dates for and hit a search button. If the database has records for the entered year, a calendar for each date is displayed, selecting the date from the database, not the current date.
Finally figured out how to do have the date set in the database display in a calender. Here's the code:
Dim strConn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\scrummingit2.mdf;Integrated Security=True;User Instance=True"
Dim sql As String = "SELECT [Year], [Autumn_Start], [Autumn_End], [Spring_Start], [Spring_End], [Summer_Start], [Summer_End], [Easter_Start], [Easter_End] FROM [Semester_Dates] WHERE ([Year] = '" + TxtAddYearDates.Text + "')"
Dim conn As New SqlConnection(strConn)
Dim objDR As SqlDataReader
Dim Cmd As New SqlCommand(Sql, conn)
conn.Open()
objDR = Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
While objDR.Read()
AutumnStartCalendar.SelectedDate = objDR("Autumn_Start")
AutumnStartCalendar.VisibleDate = objDR("Autumn_Start")
AutumnEndCalendar.SelectedDate = objDR("Autumn_End")
AutumnEndCalendar.VisibleDate = objDR("Autumn_End")
SpringStartCalendar.SelectedDate = objDR("Spring_Start")
SpringStartCalendar.VisibleDate = objDR("Spring_Start")
SpringEndCalendar.SelectedDate = objDR("Spring_End")
SpringEndCalendar.VisibleDate = objDR("Spring_End")
SummerStartCalendar.SelectedDate = objDR("Summer_Start")
SummerStartCalendar.VisibleDate = objDR("Summer_Start")
SummerEndCalendar.SelectedDate = objDR("Summer_End")
SummerEndCalendar.VisibleDate = objDR("Summer_End")
EasterStartCalendar.SelectedDate = objDR("Easter_Start")
EasterStartCalendar.VisibleDate = objDR("Easter_Start")
EasterEndCalendar.SelectedDate = objDR("Easter_End")
EasterEndCalendar.VisibleDate = objDR("Easter_End")
End While

Reading multiple rows of data using sqldatareader

I've the below sql statement as follows:
SELECT * FROM ViewSectorInvestments WHERE AccountNumber = #AccountNumber
Fields in ViewSectorInvestments:
AccountNumber
SectorName
AmountInvested
I'm trying to compute the AmountInvested in each sector against the total investments.
So the formula will be: AmountInvested/TotalInvestments * 100
my code is as follows:
string DMConnectionString = ConfigurationManager.ConnectionStrings["DMConnectionString"].ConnectionString;
SqlConnection DMConnection = new SqlConnection(DMConnectionString);
DMConnection.ConnectionString = DMConnectionString;
string DMCommandText = "SELECT Name,RiskProfile,AccountNumber,TotalInvestments FROM ViewClientDetails WHERE AccountNumber = #AccountNumber; SELECT * FROM ViewSectorInvestments WHERE AccountNumber = #AccountNumber ;SELECT * FROM ViewStockTypeInvestments WHERE AccountNumber = #AccountNumber ";
SqlCommand DMCommand = new SqlCommand(DMCommandText, DMConnection);
DMCommand.Parameters.AddWithValue("#AccountNumber", lb_AcctNum.Text);
DMConnection.Open();
SqlDataReader DMReader = DMCommand.ExecuteReader();
ArrayList SectorArray = new ArrayList();
ArrayList StockTypeArray = new ArrayList();
while (DMReader.Read())
{
CustName.Text = DMReader["Name"].ToString();
lb_Risk.Text = DMReader["RiskProfile"].ToString();
T_Investment.Text = DMReader.GetDecimal(DMReader.GetOrdinal("TotalInvestments")).ToString("N2");
Client_RiskProfile.Text = DMReader["RiskProfile"].ToString();
//encounter error when i add the datas into arraylist.
//System.IndexOutOfRangeException: SectorName
SectorArray.Add(DMReader.GetOrdinal("SectorName").ToString());
StockTypeArray.Add(DMReader.GetOrdinal("BlueChipName").ToString());
foreach( Object objReader in SectorArray){
//compute the percentage of amount invested in each sector
//check if the percentage is more than 25%
//if it is more than 25% lbMsg (an label) shows the name of the sector.
}
}
DMReader.Close();
DMConnection.Close();
}
When i test out the sql statement :
SELECT * FROM ViewSectorInvestments WHERE AccountNumber = #AccountNumber
The result i got is :
AccountNumber SectorName AmountInvested
1001 Commerce 97230.00000
1001 Construction 389350.00000
1001 Finance 222830.00000
1001 Hotel 14910.00000
1001 Loans 105070.00000
1001 Manufacturing 1232210.00000
1001 Mining/Quarrying 32700.00000
I encountered System.IndexOutOfRangeException: SectorName.
What's wrong with my code?
Please advice me. Thanks in advance.
string DMCommandText = "SELECT Name,RiskProfile,AccountNumber,TotalInvestments FROM ViewClientDetails WHERE AccountNumber = #AccountNumber; SELECT * FROM ViewSectorInvestments WHERE AccountNumber = #AccountNumber ;SELECT * FROM ViewStockTypeInvestments WHERE AccountNumber = #AccountNumber ";
This CommandText contains multiple queries. Only the results from the last SELECT statement will be returned to the SqlDataReader.
SectorArray.Add(DMReader.GetOrdinal("SectorName").ToString());
You are trying to access the column ordinal of a field called "SectorName" in your SqlDataReader. The problem causing your exception is probably that the column doesn't exist, but it's hard to say since you are using SELECT * in your CommandText.

Resources