I have a table in my database that stores data entry. theres a name column where each persons name is inserted as they scan a serial number, 3 middle columns for serial entry and the last column is the date. database sample:
i have a winform with a datagridview that populates the dates in the column header for every day of the month. what i am trying to figure out is how to populate the distinct name along with the count of their serial numbers based on what day it is in the datagridview. i can populate the names but the serial counts on specific days is getting me. Here is what my winform looks like:
and the code:
DateTime dt = DateTime.Now;
var startDate = new DateTime(dt.Year, dt.Month, 1);
int days = DateTime.DaysInMonth(dt.Year, dt.Month);
for (int i = 0; i < days; i++)
{
dataGridView1.Columns.Add("clm_" + startDate.ToShortDateString(), startDate.ToString("dd-MMM"));
startDate = startDate.AddDays(1);
}
using (SqlConnection sqlConnection = new SqlConnection(@"connection"))
{
SqlCommand sqlCmd = new SqlCommand("SELECT DISTINCT NAME FROM repair_data_entry", sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReaderName = sqlCmd.ExecuteReader();
while (sqlReaderName.Read())
{
dataGridView1.Rows.Add(sqlReaderName["NAME"].ToString());
}
sqlReaderName.Close();
}
what i need to do is pull the serial count per day per tech. like Bill Berrys serial count for a specific day shows up in that specific cell. it may be a thing where i need to set the database up differently, i don't know. and that wouldn't be a problem. i should note there aren't specific names either. there's going to be 20-30 names that change on a daily basis so my intent was something dynamic.
EDIT:
I've been fiddling with SQL fiddler and I found the query that works, However. I had to hard code the dates? How would I make them dynamic based on what's in the CREATED column since techs will be entering in data on a daily basis?
Here's the query:
SELECT NAME AS TECH,
[12/1/2020], [12/2/2020]
FROM
(SELECT NAME, REP, CREATED
FROM repair_data_entry) AS SourceTable
PIVOT
(
COUNT(REP)
FOR CREATED IN ([12/1/2020], [12/2/2020])
) AS PivotTable;
I figured out the sql Query:
DECLARE @Date AS VARCHAR(MAX),
@query AS VARCHAR(MAX)
select @dATE = STUFF((SELECT ',' + QUOTENAME(REPLACE(CONVERT(VARCHAR(10), CREATED, 101), '-', '/'))
from repair_data_entry
group by CREATED
ORDER BY CREATED
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1,1,'')
SET @query = 'SELECT NAME AS TECH, ' + @Date + '
FROM
(SELECT NAME, CREATED, REP
FROM repair_data_entry) AS S
PIVOT
(
COUNT(REP)
FOR CREATED IN ('+@Date+')
) P'
EXECUTE(@query)
This does exactly what I want. so that answers that. sqlFiddle
can anyone point me in the direction to change the date style to "MM / dd / yyyy"?
EDIT: found the answer. updated query
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.