I have a small registration Form with 4 fields - c#

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

Related

How do I get this with only One Query/SubQuery

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

I want to insert the record which is not already inserted

INSERT INTO Timetable values ('E-465458',1,1,8,10,11)
SELECT StaffID, ClassTimingId,WeekDayId,DepartmentId,ClassID,SectionID
FROM TimeTable
WHERE EXISTS (SELECT *
FROM Timetable
WHERE WeekDayId = 1 AND DepartmentId = 8 and ClassTiminng = 1 ) ;
I have table with name Timetable if WeekdayID is alredy 1 and DepartmentId=8 and ClassTiming=1 then dont insert the record it search all rows in table
Try this:
IF NOT EXISTS (
SELECT *
FROM Timetable
WHERE WeekDayId = 1
AND DepartmentId = 8
AND ClassTiming = 1
)
BEGIN
INSERT INTO Timetable (StaffID, ClassTimingId, WeekDayId, DepartmentId, ClassID, SectionID)
VALUES ('E-465458', 1, 1, 8, 10, 11)
END
You can't do both VALUES and SELECT at the same time.
INSERT INTO Timetable
SELECT 'E-465458',1,1,8,10,11
WHERE NOT EXISTS (SELECT *
FROM Timetable
WHERE WeekDayId = 1 AND DepartmentId = 8 and ClassTiminng = 1 ) ;
Or better switch to a MERGE:
MERGE INTO Timetable AS tgt
USING VALUES ('E-465458',1,1,8,10,11) AS src (StaffID, ClassTimingId,WeekDayId,DepartmentId,ClassID,SectionID)
ON tgt.WeekDayId = src.WeekDayId
AND tgt.DepartmentId = src.DepartmentId
AND tgt.ClassTimingId = src.ClassTimingId
WHEN NOT MATCHED
THEN INSERT (src.StaffID, src.ClassTimingId,src.WeekDayId,src.DepartmentId,src.ClassID,src.SectionID)
agree with irshad, you can try this to optimize the query :
IF NOT EXISTS (SELECT 1
FROM Timetable
WHERE WeekDayId = 1 AND DepartmentId = 8 and ClassTiming = 1 )
BEGIN
INSERT INTO Timetable (StaffID, ClassTimingId,WeekDayId,DepartmentId,ClassID,SectionID) VALUES ('E-465458',1,1,8,10,11)
END

Insert rows automatically

I have 3 tables:
Table 1
CustomerID Name Sname Zipcode
1 test1 test1 xxx2
2 test2 test2 yyy2
3 test3 test3 xxx2
Table 2
StaffID Name sname
1 Jack Mack
2 Jhon Addison
Table 3
ID CustomerID StaffID
1 1 1
I am not sure if SQL can do this, So in C# what I want is if StaffID 2 is not in Table 3 and if a staff wants to visit all the customers in zipcode xx2 then by click on a visit button he should be inserted for all the zipcode. So if I select Zipcode xxx2 then the query should first check if I am not visiting same Zipcode for a specific, if not then add the person into table 3 so the updated table 3 will look something like this:
ID CustomerID StaffID
1 1 1
2 1 2
3 3 2
As you can see, StaffID 2 would like to visit xxx2 zipcode as a result he gets 2 entries into Table 3 because there are two CustomerID with Zipcode same as xxx2.
I have did some online research I would this IF EXISTS (SELECT but it just add one entry. Also I guess I will be expecting 3 parameter from C# zipcode, CustomerID and StaffID
From your description it appears you just need a simple insert statement.
INSERT INTO Table3 (CustomerID, StaffID)
select CustomerID, #StaffId from Table1
where Zipcode = #zipcode
and NOT EXISTS(select StaffID from Table3 where StaffID = #staffId)
Try this sql query, assuming you are passing #StaffId, #CustomerId and #Zip as parameter
INSERT INTO Table3 (CustomerID, StaffID)
SELECT CustomerID, #StaffId FROM Table1
WHERE Zipcode = #zip
AND NOT EXISTS(SELECT StaffID FROM Table3 WHERE StaffID = #staffId
AND CustomerID = #CustomerId)

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

display count in textbox

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();

Categories

Resources