C# SQL query - try to use sum(weekly_slot) FROM group by - c#

I am trying to sum weekly_slot according to Teacher_Name from GroupOdd dbtable, however I am getting 10 values for all row. Appreciate if can correct me. Beside that, how to update GroupOdd dbtable to sort according to larger sum_weekly_slot first?
Thanks.
cmd2 = new SQLiteCommand();
cmd2 = dbConnect.CreateCommand();
//cmd2.CommandText = "DELETE FROM GroupOdd";
//cmd2.ExecuteNonQuery();
cmd2.CommandText = "SELECT Sum(Weekly_Slot) AS Sum_Weekly_Slot FROM GroupOdd group by Teacher_Name";
DataTable dt2 = new DataTable();
SQLiteDataAdapter da2 = new SQLiteDataAdapter(cmd2);
da2.Fill(dt2);
foreach (DataRow dr2 in dt2.Rows)
{
//cmd.CommandText = "INSERT INTO GroupOdd (Teacher_Name, Standard, Subject, Weekly_Slot, Balance_Slot) VALUES (#Teacher_Name, #Standard, #Subject, #Weekly_Slot, #Balance_Slot)";
cmd2.CommandText = "UPDATE GroupOdd SET Sum_Weekly_Slot = #Sum_Weekly_Slot";
//cmd2.Parameters.AddWithValue("#Sum_Weekly_Slot", dr2["Sum(Weekly_Slot)"].ToString());
cmd2.Parameters.AddWithValue("#Sum_Weekly_Slot", dr2["Sum_Weekly_Slot"].ToString());
cmd2.ExecuteNonQuery();
}

All you need is a GROUP BY clause with the MAX aggregate function:
SELECT id, MAX(rev)
FROM YourTable
GROUP BY id
Than Update it accordingly.
IF
Sum(Weekly_Slot);
is not what u looking for
try
Count(Weekly_Slot)

SELECT Teacher_Name, Sum(Weekly_Slot) AS Sum_Weekly_Slot FROM GroupOdd
group by Teacher_Name order by Sum(Weekly_Slot) desc
Check the Teacher_Names are unique, else try to use an Id (TeacherId) for Teachers. The order by Sum(Weekly_Slot) desc should sort the table by largest first.

Related

MySQL trigger + insert

i'm trying to get my current id from a table pk to insert on another table fk, my next try is set a trigger inside database.
CREATE PROCEDURE `INSERIR CODIGO DISPENSACAO` ()
CREATE TRIGGER `productInsert`
BEFORE INSERT ON `produtos_disp`
FOR EACH ROW
BEGIN
set NEW.ID_PRODISP = (select max(ID)
from dispensacao p
);
END
what I want to set max id from dispensacao table which is going to be inserted from auto_increment on insert to it, on my fk codigo_disp for every row.
Managed to get max id using a combobox as descending order.
used
MySqlConnection connection = new MySqlConnection("connectionString");
string selectQuery = "select ID from dispensacao ORDER BY id DESC LIMIT 1";
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
DataTable dt2 = new DataTable();
dt2.Load(reader);
Cmbid.DisplayMember = "ID";
Cmbid.DataSource = dt2;
this return the max id from the table and all you need to do is make it invisible so user won't change as it is a combobox

How to use two queries to find result on the basis of first query

I have two tables Repair_master and New_Equipment_info, with the query shown here, I am able to retrieve all the latest date record of maint. by grouping RID and fill the data grid.
SELECT
t1.RID
,t1.RDATE
,t1.EQ_ID
,new_equipment_info.Equipment_Name
,new_equipment_info.Complete_specification
,t1.DEPT
,t1.REPAIR_MAINT
,t1.ACTION_TAKEN
,t1.SAPRES
,t1.ATT_BY
,t1.[STATUS]
,t1.RNO
FROM
Equipment.dbo.REPAIR_MASTER t1
INNER JOIN
Equipment.dbo.new_EQUIPMENT_INFO
ON t1.EQ_ID = New_Equipment_info.Equipment_Id
INNER JOIN
(
SELECT
Eq_ID
,max(RDate) as MaxDate
FROM
Equipment.dbo.REPAIR_MASTER
group by
Eq_ID
) tm
ON t1.EQ_ID = tm.EQ_ID
and t1.RDATE = tm.MaxDate
WHERE
t1.Repair_Maint = 'maint.'
ORDER BY
t1.RDATE DESC
But I want to know the number of days from the last date filtered from query and current date.
Like this
DATEDIFF(day, MaxDate, GETDATE()) AS Difference)
Kindly advise
Further I want to enter number of days in text box and click button and show only those records having a difference greater than the value entered.
private void btnOverDue_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(connString))
{
string p = "SELECT t1.[RID],t1.[RDATE],t1.[EQ_ID],new_equipment_info.Equipment_Name,new_equipment_info.Complete_specification," +
"t1.[DEPT],t1.[REPAIR_MAINT],t1.[ACTION_TAKEN],t1.[SAPRES],t1.[ATT_BY],t1.[STATUS],t1.[RNO]FROM([Equipment].[dbo].[REPAIR_MASTER] t1 inner join[Equipment].[dbo].new_EQUIPMENT_INFO ON " +
"t1.EQ_ID = New_Equipment_info.Equipment_Id inner join (select Eq_ID, max(RDate) as MaxDate FROM [Equipment].[dbo].[REPAIR_MASTER] group by Eq_ID) tm on t1.EQ_ID=tm.EQ_ID and t1.RDATE =tm.MaxDate)" +
"where t1.Repair_Maint='maint.' ORDER BY t1.RDATE desc";
SqlCommand cmd = new SqlCommand(p, con);
SqlDataAdapter dataadapter = new SqlDataAdapter(p, con);
DataSet ds = new DataSet();
dataadapter.Fill(ds, "Repair_master");
EquipGrid.DataSource = ds;
EquipGrid.DataMember = "Repair_master";
}
}

Sum column rows where date == specific date in C#

We have a date column in an database table. We need to check if the date occurs multiple times and add the sum of another column, called 'hours_remaining'.
For example on 30/11/2017 we have two tasks with 3 and 4 in the 'hours_remaining' column. We need to sum these values and plot to a Visual Studio chart.
Currently it plots the two values separately on the chart.
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM SprintTask INNER JOIN Sprint ON SprintTask.sprint_id = Sprint.Id WHERE Sprint.Id = #sid", con);
cmd.Parameters.AddWithValue("#sid", Request.QueryString["sid"]);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet st = new DataSet();
sda.Fill(st, "task_start_date");
Chart1.DataSource = st.Tables["task_start_date"];
Chart1.Series["Series1"].XValueMember = "task_start_date";
Chart1.Series["Series1"].YValueMembers = "hours_remaining";
this.Chart1.Titles.Add("This is a test chart ");
Chart1.Series["Series1"].ChartType = SeriesChartType.Line;
Chart1.Series["Series1"].IsValueShownAsLabel = true;
As #mjwills wrote in his comment, you need to use group by and sum:
SELECT task_start_date, SUM(hours_remaining) As hours_remaining
FROM SprintTask
INNER JOIN Sprint ON SprintTask.sprint_id = Sprint.Id
GROUP BY task_start_date
WHERE Sprint.Id = #sid

Column 'RecordsDate.StartDateTime' is invalid in the HAVING clause because it is

*sorry the title cannot be too long so I have to cut it down.
hi, I would like to get the total duration from my database table where the
dateID is 1 and the year of the datetime is 2016 using SQL Query in asp.net c#. I tried using the codes below but it does not work. It says 'Additional information: Column 'RecordsDate.StartDateTime' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.' Can anyone tell me what's wrong with my SQL Query please? Thanks a lot :)
float totalDuration = 0f;
string sQuery = "SELECT sum(Duration) AS TotalDuration FROM RecordsDate WHERE DateID='1' HAVING DATEPART(yyyy, StartDateTime) = '2016'";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(sQuery, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
totalDuration = float.Parse(dr["TotalDuration"].ToString());
}
conn.Close();
dr.Close();
Provide group by with some column name from the table:
select sum(duration) as totalduration from recordsdate
where dateid='1' having datepart(yyyy, startdatetime) = '2016'
group by ?

How to sort and rank and select a unique value?

I need to get the rank, from a group of players by sorting using sql query.
i have the query.
query = #"SET #rank=0;
SELECT player_ID,player_name,HP,#rank:=#rank+1 As Rank
FROM player_profile ORDER BY HP DESC;"
the problem is i just need the specified player's rank from this query.
Since rank is generated using SQL, i can't use WHERE clause. That will one bring one player from DB, resulting one rank.
I tried to get all of them into a datatable and then filter the single value out of it.
con.Open();
MySqlDataAdapter dt = new MySqlDataAdapter();
DataTable tt = new DataTable();
string query = #"SET #rank=0;
SELECT player_ID,player_name,HP,#rank:=#rank+1 As Rank
FROM player_profile ORDER BY HP DESC;";
MySqlCommand cm1 = new MySqlCommand(query, con);
dt.SelectCommand = cm1;
dt.Fill(tt);
con.Close();
DataRow[] foundRows = tt.Select("player_name=" + Label2.Text); // Error:Cannot find column ["Column name"]
foreach (DataRow dr in foundRows)
{
Label32.Text = dr["Rank"].ToString();
}
this is how my table looks
http://pastebin.com/7KWJ9bn3
any help is appreciated.
I'm a big proponent of not putting business logic in your SQL which it seems like your doing here. The below code is my updated version of your code which should be logically equivalent without having to do any calculation on the SQL side of things.
I'm not entirely sure what you are trying to achieve (is this example code?) so if you can provide more info I can refine this some more, but again this will do the exact same thing in a "better" fashion.
con.Open();
MySqlDataAdapter dt = new MySqlDataAdapter();
DataTable tt = new DataTable();
string query = #"SET #rank=0;
SELECT player_ID,player_name,HP
FROM player_profile ORDER BY HP DESC;";
MySqlCommand cm1 = new MySqlCommand(query, con);
dt.SelectCommand = cm1;
dt.Fill(tt);
con.Close();
DataRow[] foundRows = tt.Select("player_name=" + Label2.Text); // Error:Cannot find column ["Column name"]
int count = 1;
foreach (DataRow dr in foundRows)
{
Label32.Text = count;//dr["Rank"].ToString();
count++;
}
What about selecting from the resulting table?
string query = #"SET #rank=0;
Select a.Rank from (SELECT player_ID,#rank:=#rank+1 As Rank
FROM player_profile ORDER BY HP DESC) a where player_ID=#1";

Categories

Resources