I have a simple problem. I have a table in dataset designer that have this query
SELECT COUNT(Sex) AS Male, COUNT(Sex) AS Female
FROM tblPersonalInfo
can you please show me how to display the male and female count in 2 textboxes? and can you please check if my query is correct? i'm a newbie in visual studio c# 2010.
form my previous projects, i use these to retrieve data from database and display in textbox.
public MAINDATABASEDataSet.tblPositionDataTable GetPositionData(string data)
{
MAINDATABASEDataSetTableAdapters.tblPositionTableAdapter ReturnPosition = new MAINDATABASEDataSetTableAdapters.tblPositionTableAdapter();
return ReturnPosition.GetDataByPosition(this.txtSearch.Text.Trim());
}
}
private void btnCompleteSearch_Click(object sender, EventArgs e)
{
MAINDATABASEDataSet.tblPositionDataTable GetPositionCommand1 = GetPositionData(this.txtSearch.Text);
MAINDATABASEDataSet.tblPositionRow GetPositionCommand2 = (MAINDATABASEDataSet.tblPositionRow)GetPositionCommand1.Rows[0];
this.txtMainPosition.Text = GetPositionCommand2.Position.ToString();
}
and i use this query:
SELECT Position
FROM tblPosition
WHERE (ID = #IDMain)
Without seeing any code or background it's impossible to answer properly but as it stands your query will produce the same count for Male as for Female. to count just the males you would need something like
SELECT COUNT(Sex) AS Male,
FROM tblPersonalInfo
WHERE Sex = 'Male'
and then a second query for female. Or else
SELECT COUNT(Sex)
FROM tblPeroncalInfo
GROUP BY Sex
Or if you really need them as spearate columns:
SELECT SUM(CASE WHEN Sex = 'Male' 1 ELSE 0 END) AS Male,
SUM(CASE WHEN Sex = 'Female' 1 ELSE 0 END) AS Female
FROM tblPersonalInfo
The query should be like
SELECT COUNT(Sex) from tblPersonalInfo GROUP BY SEX
you need to modify your query like this:
SELECT COUNT(sex) FROM tblPersonalInfo WHERE sex = 'male'
int maleCount = (int)cmd.ExecuteScaler();
SELECT COUNT(sex) FROM tblPersonalInfo WHERE sex = 'female'
int femaleCount = (int)cmd.ExecuteScaler();
You can show the count in two text boxes as
textBoxMale.text = maleCount.ToString();
textBoxFemale.text = femaleCount.Tostring();
Related
I have a table 'Employee' with name, surname, dateOfBirth and so one.
This table doesn't contain Age column, but I need to compute and display age in DataGridView with Name.
Like this:
John 30
Mary 25
The problem is when I execute query
select FirstName, DATEDIFF(yy, DateOfBirth, GETDATE()) as Age from Empoyee
in SQL Server, I get what I need, but when I try to fill DataGridView the Age column is displayed incorrect.
edDataGridView.AutoGenerateColumns = false;
edDataGridView.DataSource = context.Empoyee.SqlQuery("SELECT FirstName, DATEDIFF(yy, DateOfBirth, GETDATE()) as Age from Empoyee").ToList();
Please tell me how to do this right. May be I should use LINQ?
Solved by myself, thank all))
edDataGridView.AutoGenerateColumns = false;
var query = from e in context.Empoyee
select new
{
e.FirstName, Age = DateTime.Now.Year - e.DateOfBirth.Year
};
edDataGridView.DataSource = query.ToList();
I have this database table:
Name Beneficiary GenderBeneficiary
---------------------------------------
Karla Karla Female
Carl Mandy Female
Mark Lu Male
Erik Math Male
Jhon Jhon Male
And I need this
Gender
Description Male Female Total
-------------------------------------------
Employee 1 1 2
Familiar 2 1 3
Total 3 2 5
If the name is the same of the beneficiary is an Employee, if not is a familiar.
I get a nice result using UNION with 4 queries and the structure in SQL Server is:
Updated: stored procedure used
USE [BdDiscountCardSystem]
GO
SET ANSI_NULLS ONGO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[FillTableOne]
#dateStart DATETIME,
#dateEnd DATETIME
AS
BEGIN
SET NOCOUNT ON;
SELECT
COUNT (GenderBeneficiary) AS Gender
FROM
CartaDescuento
WHERE
Name = BeneficiaryName
AND GenderBeneficiary = 'Male'
AND DateS BETWEEN #dateStart AND #dateEnd
UNION
SELECT
COUNT (GenderBeneficiary)
FROM
CartaDescuento
WHERE
Name = BeneficiaryName
AND GenderBeneficiary = 'Female'
AND DateS BETWEEN #dateStart AND #dateEnd
UNION
SELECT
COUNT (GenderBeneficiary)
FROM
CartaDescuento
WHERE
Name != BeneficiaryName
AND GenderBeneficiary = 'Male'
AND DateS BETWEEN #dateStart AND #dateEnd
UNION
SELECT
COUNT (GenderBeneficiary)
FROM
CartaDescuento
WHERE
Name != BeneficiaryName
AND GenderBeneficiary = 'Female'
AND DateS BETWEEN #dateStart AND #dateEnd
END
The result:
Title
1
2
1
1
I'm calling the stored procedure from C# like this:
public void GetTableOne()
{
string dateStart = dateInicio.Value.ToShortDateString();
string dateEnd = dateFinal.Value.ToShortDateString();
try
{
con.Open();
SqlCommand cmd = new SqlCommand("FillTableOne", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("dateStart", dateStart);
cmd.Parameters.AddWithValue("dateEnd", dateEnd);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "¡Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close();
}
}
Updated: but I only get 1 query, not the UNIONS in the stored procedure:
Title
1
Updated: I didn't put the query or the code, because that doesn't work. I'm looking for help in structuring that in a single query. I assumed that it was not necessary to put anything other than the tables and the result that I want, in this way to be able to accommodate the columns as the report requires.
Well, anyone know a better option to get in only one query?
Additional question: I'm reporting with iTextSharp and is kinda tedious typing 120 code lines to get and structure one simple table. Any suggestions on how to get a better reporter in C#?
This isn't exactly the structure you asked for but it gets back all of the data in one query:
SELECT
SUM(CASE WHEN Name != Beneficiary AND GenderBeneficiary= 'Female' THEN 1 ELSE 0 END) AS [FemaleFamiliars],
SUM(CASE WHEN Name != Beneficiary AND GenderBeneficiary= 'Male' THEN 1 ELSE 0 END) AS [MaleFamiliars],
SUM(CASE WHEN Name = Beneficiary AND GenderBeneficiary= 'Female' THEN 1 ELSE 0 END) AS [FemaleEmployees],
SUM(CASE WHEN Name = Beneficiary AND GenderBeneficiary= 'Male' THEN 1 ELSE 0 END) AS [MaleEmployees],
SUM(CASE WHEN GenderBeneficiary= 'Female' THEN 1 ELSE 0 END) AS [TotalFemales],
SUM(CASE WHEN GenderBeneficiary= 'Male' THEN 1 ELSE 0 END) AS [TotalMales],
SUM(CASE WHEN Name != Beneficiary THEN 1 ELSE 0 END) AS [TotalFamiliar],
SUM(CASE WHEN Name = Beneficiary THEN 1 ELSE 0 END) AS [TotalEmployees],
COUNT(*) AS [GrandTotal]
FROM Employees
Here is another approach to this. It requires two queries and a UNION ALL but not a huge deal. It is actually quite a few less characters than the previous answer. :)
declare #Something table
(
Name varchar(10)
, Beneficiary varchar(10)
, GenderBeneficiary varchar(10)
)
insert #Something values
('Karla', 'Karla', 'Female')
,('Carl', 'Mandy', 'Female')
,('Mark', 'Lu', 'Male')
,('Erik', 'Math', 'Male')
,('Jhon', 'Jhon', 'Male')
select case when s.Name = s.Beneficiary then 'Employee' else 'Familiar' end
, sum(case when GenderBeneficiary = 'Male' then 1 end)
, sum(case when GenderBeneficiary = 'Female' then 1 end)
, count(*)
from #Something s
group by case when s.Name = s.Beneficiary then 'Employee' else 'Familiar' end
UNION ALL
select Description = 'Total'
, sum(case when GenderBeneficiary = 'Male' then 1 end)
, sum(case when GenderBeneficiary = 'Female' then 1 end)
, count(*)
from #Something s
The fields are
employeeID int
name varchar
Gender int (0 = male, 1 = female)
Date datetime
Now if i am writing select query like this
select employeeID,name,Gender,Date
from empTable
where employeeID=#id
I get result
'101','cccc','1','11/1/2014'
But i need a query its give me
'101','cccc','Female','11/1/2014'
If this is Sql Server you can use a CASE statement.
select employeeID
,name
,case when Gender = 1 then 'Female' else 'Male' end AS Gender
,Date
from empTable
where employeeID=#id
IIF statement
select employeeID
,name
, IIF(Gender = 1, 'Female', 'Male') AS Gender
,Date
from empTable
where employeeID=#id
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
How can this query be transform to linq
SELECT materialId, SUM(totalAmount) as quantity FROM Inventory
It's the sum part that I don't know how...
query = from inv in context.Inventory
select new MaterialQuantity()
{
MaterialId = inv.materialId,
Quantity = ??
};
EDIT
Trying to sum the value of totalAmount.
It's a view that is
materialId totalSum and other fields
1 5
1 10
1 20
So I want my linq to return me
MaterialId = 1, Quantity = 35
I'm going to give a complete guess here... assuming your inventory has multiple rows with the same materialId and you want to sum in those groups, you could use:
var query = from inv in content.Inventory
group inv.totalAmount by inv.materialId into g
select new { MaterialId = g.Key, Quantity = g.Sum() };
If you're not trying to group though, you'll need to clarify your question. Sample data and expected output would help.