SQL Server : searching for occurrences in different months - c#
I am trying to do a project which uses Visifire to display graphed data. It takes in a single DataTable. I need to create an SQL query that searches a date column for a particular month (format is: Friday, 03 November 2017) and then stores how many times that month is repeated. It has to do this for all 12 months. This is done in C# in visual studio. Currently, it displays no data on the line graph.
public DataTable ReadDataMonthlyBooked()
{
// Declare references (for table, reader and command)
DataTable monthlyBookedTable = new DataTable();
SqlDataReader reader;
SqlCommand command;
string selectString = "SELECT COUNT (BookingNum) AS Bookings "
+ "FROM Booking "
+ "WHERE Booking.EndDate LIKE 'January' "
+ "AND Booking.EndDate LIKE 'February' "
+ "AND Booking.EndDate LIKE 'March' "
+ "AND Booking.EndDate LIKE 'April' "
+ "AND Booking.EndDate LIKE 'May' "
+ "AND Booking.EndDate LIKE 'June' "
+ "AND Booking.EndDate LIKE 'July' "
+ "AND Booking.EndDate LIKE 'August' "
+ "AND Booking.EndDate LIKE 'September' "
+ "AND Booking.EndDate LIKE 'October' "
+ "AND Booking.EndDate LIKE 'November' "
+ "AND Booking.EndDate LIKE 'December'";
try
{
// Create a new command
command = new SqlCommand(selectString, cnMain);
// open the connection
cnMain.Open();
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
// read data from readerObject and load in table
monthlyBookedTable.Load(reader);
reader.Close(); //close the reader
cnMain.Close(); //close the connection
return monthlyBookedTable;
}
catch (Exception ex)
{
return (null);
}
}
This is the current SQL query I have and I hope its hopelessly wrong with logic errors but I do not know SQL well enough.
select 'Friday, 03 November 2017'
select cast('03 November 2017' as date)
select SUBSTRING('Friday, 03 November 2017', CHARINDEX(',', 'Friday, 03 November 2017') + 2, 100)
select cast(SUBSTRING('Friday, 03 November 2017', CHARINDEX(',', 'Friday, 03 November 2017') + 2, 100) as date)
select datepart(month, cast(SUBSTRING('Friday, 03 November 2017', CHARINDEX(',', 'Friday, 03 November 2017') + 2, 100) as date))
select datepart(month, cast(Booking.EndDate, CHARINDEX(',', Booking.EndDate) + 2, 100) as date))
, COUNT (BookingNum) AS Bookings "
from booking
group by datepart(month, cast(Booking.EndDate, CHARINDEX(',', Booking.EndDate) + 2, 100) as date))
You'll need a group by, like this
SELECT COUNT(BookingNum) as Bookings, MONTH(EndDate) as Month
FROM Booking
GROUP BY MONTH(EndDate)
But as your EndDate is a varchar, you'll have to extract the month
SELECT COUNT(BookingNum) as Bookings
, SUBSTRING(EndDate,
CHARINDEX(',',EndDate) + 4,
CHARINDEX(' ',EndDate, CHARINDEX(',',EndDate) + 5) - CHARINDEX(',',EndDate) + 4)
FROM Booking
GROUP BY SUBSTRING(EndDate,
CHARINDEX(',',EndDate) + 4,
CHARINDEX(' ',EndDate, CHARINDEX(',',EndDate) + 5) - CHARINDEX(',',EndDate) + 4)
There may be a better way to do this (cursors maybe?) but basically you want to get the location of the first ',' and add 4 to get the month (assuming the date is always 2 digits like in your example) and then use that as a start index for a search of the first blank (that'll be the end of the month name) and substract the first index we found to get the length fo the month.
So, basically, just change the date to a DATE field
or cast it
SELECT COUNT(BookingNum) as Bookings, MONTH(CONVERT(DATE, EndDate)) as Month
FROM Booking
GROUP BY MONTH(CONVERT(DATE, EndDate))
But I don't know if the format you are using will be interpreted correctly by the engine.
The error is in your SQL statement.
SELECT
COUNT(BookingNum) AS Bookings
FROM
Booking
WHERE
Booking.EndDate LIKE '%January%',
AND Booking.EndDate LIKE '%February%',
AND Booking.EndDate LIKE '%March%',
AND Booking.EndDate LIKE '%April%',
AND Booking.EndDate LIKE '%May%',
AND Booking.EndDate LIKE '%June%',
AND Booking.EndDate LIKE '%July%',
AND Booking.EndDate LIKE '%August%',
AND Booking.EndDate LIKE '%September%',
AND Booking.EndDate LIKE '%October%',
AND Booking.EndDate LIKE '%November%',
AND Booking.EndDate LIKE '%December%',
You try to get a record where the month is every month in the year at the same time.
If I'm right, you try to get the number of bookings per month.
So it should look something much more like
SELECT
SUM(CASE WHEN Booking.EndDate LIKE '%January%' THEN 1 ELSE 0 END) AS JanuaryBookings,
SUM(CASE WHEN Booking.EndDate LIKE '%February%' THEN 1 ELSE 0 END) AS FebruaryBookings,
SUM(CASE WHEN Booking.EndDate LIKE '%March%' THEN 1 ELSE 0 END) AS MarchBookings,
SUM(CASE WHEN Booking.EndDate LIKE '%April%' THEN 1 ELSE 0 END) AS AprilBookings,
SUM(CASE WHEN Booking.EndDate LIKE '%May%' THEN 1 ELSE 0 END) AS MayBookings,
SUM(CASE WHEN Booking.EndDate LIKE '%June%' THEN 1 ELSE 0 END) AS JuneBookings,
SUM(CASE WHEN Booking.EndDate LIKE '%July%' THEN 1 ELSE 0 END) AS JulyBookings,
SUM(CASE WHEN Booking.EndDate LIKE '%August%' THEN 1 ELSE 0 END) AS AugustBookings,
SUM(CASE WHEN Booking.EndDate LIKE '%September%' THEN 1 ELSE 0 END) AS SeptemberBookings,
SUM(CASE WHEN Booking.EndDate LIKE '%October%' THEN 1 ELSE 0 END) AS OctoberBookings,
SUM(CASE WHEN Booking.EndDate LIKE '%November%' THEN 1 ELSE 0 END) AS NovemberBookings,
SUM(CASE WHEN Booking.EndDate LIKE '%December%' THEN 1 ELSE 0 END) AS DecemberBookings
FROM
Booking
Related
date_trunc interval in PostgreSQL 15 minutes
const string query = "SELECT worker, date_trunc('hour', created) AS created, AVG(hashrate) AS hashrate, " + "AVG(sharespersecond) AS sharespersecond FROM minerstats " + "WHERE poolid = #poolId AND miner = #miner AND created >= #start AND created <= #end " + "GROUP BY date_trunc('hour', created), worker " + "ORDER BY created, worker;"; This query displays the time periods of hours. how to make 15 minutes?
Here is one option: date_trunc('hour', created) + extract(minute from created)::int / 15 * interval '15' minute
Get sum of time column in sql server
What I tried is: select cast(sum(datediff(second,0,totalhr))/3600 as varchar(12)) + ':' + right('0' + cast(sum(datediff(second,0,totalhr))/60%60 as varchar(2)),2) + ':' + right('0' + cast(sum(datediff(second,0,totalhr))%60 as varchar(2)),2) as total FROM checkinout where YEAR(date)=2019 and MONTH(date)=09 and userid=5 It giving wrong output 112:53:04 the right answer should be 116:30:04
If the totalhr column type is time and the format is hh:mm:ss, For SQL Server: DATEADD (datepart , number , date ) SELECT DATEADD (ms, SUM (DATEDIFF (ms, '00:00:00.000', totalhr)), '00:00:00.000') AS total FROM checkinout WHERE YEAR(date) = 2019 AND MONTH(date) = 9 AND userid = 5; This function adds a specified number value (as a signed integer) to a specified datepart of an input date value, and then returns that modified value. the above condition will return the calculated Date and Time but if you want just the hh:mm:ss in two digit format you can use: SELECT FORMAT(hrs, '0#') + ':' + FORMAT(mins, '0#') + ':' + FORMAT(secs, '0#') as total FROM (SELECT hrs + (((((mins * 60) + (secs - (secs % 60))) / 60) - ((((mins * 60) + (secs - (secs % 60))) / 60) % 60)) / 60) AS hrs, (((mins * 60) + (secs - (secs % 60))) / 60) % 60 AS mins, secs % 60 AS secs FROM ( SELECT SUM(116) AS hrs, // you have to replace the number with your column SUM(30) AS mins, // you have to replace the number with your column SUM(04) AS secs // you have to replace the number with your column ) AS dateSplit) AS total
try running below query SELECT cast(sum(DATEPART(HOUR,totalhr)) as varchar(max)) + ':' + cast(sum(DATEPART(MINUTE,totalhr)) as varchar(max)) + ':' + cast(sum(DATEPART(SECOND,totalhr)) as varchar(max)) FROM checkinout
How to convert Int to Varchar
I tried to convert Int to Varchar but I'm unable to get output. Can anyone suggest any other way to do so? I have below query and need to cast StoreNo (int) to a varchar: ALTER PROCEDURE [dbo].[getrevenue] #date1 DATE, #date2 DATE, #StoreNo NVARCHAR(max) AS BEGIN DECLARE #sql_test NVARCHAR(max) --SET #StoreNo='68,78,104' SET #sql_test = 'SELECT t1.transtoreno AS StoreNO ,t3.NAME AS NAME ,t1.Dealdate AS DATE ,t1.UKEI AS UKEI ,t2.SubTotal AS SubTotal ,ISNULL(t2.SubTotalDiscount, 0) AS SubToatlDiscount ,ISNULL(t1.twoeyesSubtotalDiscount, 0) AS TwoeyeSubTotalDiscount ,t2.ValueInquiries AS TotalDiscount ,t2.NetSale AS Netsale ,t2.TotalSale AS ToatlSale ,t2.Cash AS Cash ,ISNULL(t2.GiftVochuer, 0) AS GiftVochuer ,ISNULL(t2.Card, 0) AS Card ,ISNULl(t2.Suica, 0) AS Suica ,t2.WONPOINT AS WAONPOINT ,t1.TaxExemption AS TAXExemption ,t2.TaxTotal AS TaxTotal ,t2.Returngoods AS Returngoods ,t2.Regiminus AS RegiMinus ,t2.PrintRecipt AS printrecipt ,ISNULL(t1.Visitorcount, 0) AS VisitorCount FROM ( SELECT CAST(StoreNo AS NVARCHAR) AS transtoreno ,(DealDate) AS Dealdate ,SUM(SalePrice) AS UKEI ,SUM(TansuNebikiPrice) AS twoeyesdicount ,SUM(SubTotalNebiki2Price) AS twoeyesSubtotalDiscount ,SUM(TotalSalePrice - Si1Tax - RegiMinusNo) AS Netsale ,SUM(SpecialConsumptionTaxPrice) AS TaxExemption ,Sum(RegiMinusNo) AS Receiptissue ,SUM(VisitorCount) AS Visitorcount FROM POS_TtlTran GROUP BY StoreNo ,DealDate ) t1 LEFT OUTER JOIN ( SELECT DATE AS D ,cast(StoreNo AS NVARCHAR) AS s ,SUM(CASE WHEN SerialNo LIKE 23 THEN DayTotalAmt ELSE 0 END) AS Cash ,SUM(CASE WHEN SerialNo LIKE 31 THEN DayTotalAmt ELSE 0 END) AS Card ,SUM(CASE WHEN SerialNo LIKE 30 THEN DayTotalAmt ELSE 0 END) AS GiftVochuer ,SUM(CASE WHEN SerialNo LIKE 138 THEN DayTotalAmt ELSE 0 END) AS Returngoods ,SUM(CASE WHEN SerialNo LIKE 160 THEN DayTotalAmt ELSE 0 END) AS PrintRecipt ,SUM(CASE WHEN SerialNo LIKE 304 THEN DayTotalAmt ELSE 0 END) AS Suica ,SUM(CASE WHEN SerialNo LIKE 26 THEN DayTotalAmt ELSE 0 END) AS WONPOINT ,SUM(CASE WHEN SerialNo LIKE 139 THEN DayTotalAmt ELSE 0 END) AS Regiminus ,SUM(CASE WHEN SerialNo LIKE 4 THEN DayTotalAmt ELSE 0 END) AS SubToTal ,SUM(CASE WHEN SerialNo LIKE 7 THEN DayTotalAmt ELSE 0 END) AS SubTotalDiscount ,SUM(CASE WHEN SerialNo LIKE 8 THEN DayTotalAmt ELSE 0 END) AS TwoeyesubTotalDiscount ,SUM(CASE WHEN SerialNo LIKE 18 THEN DayTotalAmt ELSE 0 END) AS ValueInquiries ,SUM(CASE WHEN SerialNo LIKE 22 THEN DayTotalAmt ELSE 0 END) AS TotalSale ,SUM(CASE WHEN SerialNo LIKE 114 THEN DayTotalAmt ELSE 0 END) AS TaxTotal ,SUM(CASE WHEN SerialNo LIKE 2 THEN DayTotalAmt ELSE 0 END) AS NetSale FROM POS_FinTtl GROUP BY StoreNo ,DATE ) t2 ON t1.transtoreno = t2.s AND t1.Dealdate = t2.D LEFT OUTER JOIN ( SELECT StoreNo AS No ,StoreName AS NAME FROM Store ) t3 ON t2.s = t3.No WHERE ( t1.transtoreno IN (''' + CAST(#StoreNo AS NVARCHAR(max)) + ''') AND (t1.Dealdate between ''' + CAST(#date1 AS VARCHAR(30)) + ''' AND ''' + CAST(#date2 AS VARCHAR(30)) + '''))' END
Hope this one will work ALTER PROCEDURE [dbo].[getrevenue] #date1 DATE ,#date2 DATE ,#StoreNo NVARCHAR(max) ` AS BEGIN DECLARE #sql_test NVARCHAR(max) --SET #StoreNo='68,78,104' SET #sql_test ='SELECT t1.transtoreno AS StoreNO ,t3.NAME AS NAME ,t1.Dealdate AS DATE ,t1.UKEI AS UKEI ,t2.SubTotal AS SubTotal ,ISNULL(t2.SubTotalDiscount, 0) AS SubToatlDiscount ,ISNULL(t1.twoeyesSubtotalDiscount, 0) AS TwoeyeSubTotalDiscount ,t2.ValueInquiries AS TotalDiscount ,t2.NetSale AS Netsale ,t2.TotalSale AS ToatlSale ,t2.Cash AS Cash ,ISNULL(t2.GiftVochuer, 0) AS GiftVochuer ,ISNULL(t2.Card, 0) AS Card ,ISNULl(t2.Suica, 0) AS Suica ,t2.WONPOINT AS WAONPOINT ,t1.TaxExemption AS TAXExemption ,t2.TaxTotal AS TaxTotal ,t2.Returngoods AS Returngoods ,t2.Regiminus AS RegiMinus ,t2.PrintRecipt AS printrecipt ,ISNULL(t1.Visitorcount, 0) AS VisitorCount FROM ( SELECT CAST(StoreNo AS NVARCHAR) AS transtoreno ,(DealDate) AS Dealdate ,SUM(SalePrice) AS UKEI ,SUM(TansuNebikiPrice) AS twoeyesdicount ,SUM(SubTotalNebiki2Price) AS twoeyesSubtotalDiscount ,SUM(TotalSalePrice - Si1Tax - RegiMinusNo) AS Netsale ,SUM(SpecialConsumptionTaxPrice) AS TaxExemption ,Sum(RegiMinusNo) AS Receiptissue ,SUM(VisitorCount) AS Visitorcount FROM POS_TtlTran GROUP BY StoreNo ,DealDate ) t1 LEFT OUTER JOIN ( SELECT DATE AS D ,cast(StoreNo AS NVARCHAR) AS s ,SUM(CASE WHEN SerialNo LIKE 23 THEN DayTotalAmt ELSE 0 END) AS Cash ,SUM(CASE WHEN SerialNo LIKE 31 THEN DayTotalAmt ELSE 0 END) AS Card ,SUM(CASE WHEN SerialNo LIKE 30 THEN DayTotalAmt ELSE 0 END) AS GiftVochuer ,SUM(CASE WHEN SerialNo LIKE 138 THEN DayTotalAmt ELSE 0 END) AS Returngoods ,SUM(CASE WHEN SerialNo LIKE 160 THEN DayTotalAmt ELSE 0 END) AS PrintRecipt ,SUM(CASE WHEN SerialNo LIKE 304 THEN DayTotalAmt ELSE 0 END) AS Suica ,SUM(CASE WHEN SerialNo LIKE 26 THEN DayTotalAmt ELSE 0 END) AS WONPOINT ,SUM(CASE WHEN SerialNo LIKE 139 THEN DayTotalAmt ELSE 0 END) AS Regiminus ,SUM(CASE WHEN SerialNo LIKE 4 THEN DayTotalAmt ELSE 0 END) AS SubToTal ,SUM(CASE WHEN SerialNo LIKE 7 THEN DayTotalAmt ELSE 0 END) AS SubTotalDiscount ,SUM(CASE WHEN SerialNo LIKE 8 THEN DayTotalAmt ELSE 0 END) AS TwoeyesubTotalDiscount ,SUM(CASE WHEN SerialNo LIKE 18 THEN DayTotalAmt ELSE 0 END) AS ValueInquiries ,SUM(CASE WHEN SerialNo LIKE 22 THEN DayTotalAmt ELSE 0 END) AS TotalSale ,SUM(CASE WHEN SerialNo LIKE 114 THEN DayTotalAmt ELSE 0 END) AS TaxTotal ,SUM(CASE WHEN SerialNo LIKE 2 THEN DayTotalAmt ELSE 0 END) AS NetSale FROM POS_FinTtl GROUP BY StoreNo ,DATE ) t2 ON t1.transtoreno = t2.s AND t1.Dealdate = t2.D LEFT OUTER JOIN ( SELECT StoreNo AS No ,StoreName AS NAME FROM Store ) t3 ON t2.s = t3.No WHERE ( t1.transtoreno IN (''' + CONVERT(varchar(MAX), #StoreNo) + ''') AND (t1.Dealdate between ''' + CAST(#date1 AS VARCHAR(30)) + ''' AND ''' + CAST(#date2 AS VARCHAR(30)) + '''))' END
where (t1.transtoreno IN (''' + CAST(#StoreNo AS nvarchar(max)) + ''') Should be where (t1.transtoreno IN (''' + replace(CAST(#StoreNo AS nvarchar(max)),',',''',''') + ''')
How I calc range of date's from 2 numbers to 2 strings
I want all people that there age is 27 how i calc the start and the end date? ss.startAge = (DateTime.Now.Year - startAge).ToString() + "-" + DateTime.Now.ToString("MM") + "-" + DateTime.Now.ToString("dd"); ss.endAge = (DateTime.Now.Year - (endAge-1)).ToString() + "-" + DateTime.Now.ToString("MM") + "-" + DateTime.Now.ToString("dd"); i know that i need to sub 1 day but if the end age is need to be 1999-12-31 because the calc is above is give 2000-01-01 how i need to write the code that the end age will be correct how i calc the end date correctly?
sum of columns that are already sum in sql
SELECT DISTINCT emp_no, sum(CASE WHEN isnull(PresAbs,0)='WO' THEN 1 ELSE 0 END) WO, sum(CASE WHEN isnull(PresAbs,0)='WP' THEN 1 ELSE 0 END) WP, sum(CASE WHEN isnull(PresAbs,0)='HL' THEN 1 ELSE 0 END) HL, sum(CASE WHEN isnull(PresAbs,0)='A' THEN 1 ELSE 0 END) A,**sum(WO+WP+HL+A)** from TRN_ATTN072013 WHERE CONVERT(varchar,Tdate,112)>'20130712' and CONVERT(varchar,Tdate,112)<'20130717' group by emp_no ORDER BY emp_no i want to sum up this columns WO,WP,HL,A how do i sum these columns
If this is SQL server then you can use CTE with tablesum as ( SELECT DISTINCT emp_no, sum(CASE WHEN isnull(PresAbs,0)='WO' THEN 1 ELSE 0 END) WO, sum(CASE WHEN isnull(PresAbs,0)='WP' THEN 1 ELSE 0 END) WP, sum(CASE WHEN isnull(PresAbs,0)='HL' THEN 1 ELSE 0 END) HL, sum(CASE WHEN isnull(PresAbs,0)='A' THEN 1 ELSE 0 END) A from TRN_ATTN072013 WHERE CONVERT(varchar,Tdate,112) > '20130712' and CONVERT(varchar,Tdate,112) < '20130717' group by emp_no ) select t.*, t.WO + t.WP + t.HL + t.A from tablesum t order by t.emp_no
in mysql ;) SELECT emp_no, wo+wp+hl+A FROM (SELECT DISTINCT emp_no, sum(CASE WHEN isnull(PresAbs,0)='WO' THEN 1 ELSE 0 END) WO, sum(CASE WHEN isnull(PresAbs,0)='WP' THEN 1 ELSE 0 END) WP, sum(CASE WHEN isnull(PresAbs,0)='HL' THEN 1 ELSE 0 END) HL, sum(CASE WHEN isnull(PresAbs,0)='A' THEN 1 ELSE 0 END) A,**sum(WO+WP+HL+A)** from TRN_ATTN072013 WHERE CONVERT(varchar,Tdate,112)>'20130712' and CONVERT(varchar,Tdate,112)<'20130717' group by emp_no ORDER BY emp_no) AS SUB_Q;