How do i find the total number of records created on a given day using T-SQL? - database

I need to find out the total number of records that were created on a given day.
e.g.
ID CreatedDate
1 17/07/2009
2 12/07/2009
3 17/07/2009
4 05/07/2009
5 12/07/2009
6 17/07/2009
Output:
3 Records were created on 17/07/2009
2 Records were created on 12/07/2009
1 Record was created on 05/07/2009
EDIT
Upon testing the second suggestion made by Chris Roberts of including the formatting in the SQL i get this error:
Syntax error converting the varchar value ' Records were created on ' to a column of data type int.
Does anyone know how to rework the solution so that it works?

You should be able to get the data you're after with the following SQL...
SELECT COUNT(ID), CreatedDate
FROM MyTable
GROUP BY CreatedDate
Or - if you want to do the formatting in the SQL, too...
SELECT CONVERT(varchar, COUNT(ID)) + ' Records were created on ' + CONVERT(varchar, CreatedDate)
FROM MyTable
GROUP BY CreatedDate
Good luck!

Is the column actually a timestamp? In which case you will need to apply a function to remove the time component, e.g.:
SELECT COUNT(*), date(CreatedDate) FROM MyTable GROUP BY date(CreatedDate)
I don't know what the function is in T-SQL, it's date() in MySQL and trunc() in Oracle. You may even have to do a to_string and remove the end of the string and group by that if you lack this.
Hope this helps.

select count(*), CreatedDate from table group by CreatedDate order by count(*) DESC

Related

Query Multiple Rows Based on Combination of Columns and Criteria

I have the following table that shows details for tickets entered.
I am trying to query this table based on the following
1) Tickets that have the same Description AND Notes AND appear 2X in an hour.
OR
2) Tickets that have the same Description AND Notes AND appear 3X or more.
Therefore, the resulting table should be the following.
I tried using HAVING but couldn't figure out how to include both of the
Description and Notes criteria. I tried to use LAG to see if the previous
record is entered within an hour but that didn't work.
How can I query this? I appreciate any advice on this.
Here's the query to create this table.
Try this one, maybe you have to change any column name. This select should group by date hh:mm and take all entries with 2 or more ocurrences in the same hour.
select Description,
Notes,
convert(varchar(10),Entered,120) + ' '+ convert(varchar(2), datepart(hour,Entered)),
count(*)
from WorkEntries
group by Description,
Notes,
convert(varchar(10),Entered,120) + ' '+ convert(varchar(2), datepart(hour,Entered))
having count(*) > 1
Hope it helps!

SQL Error message: Column XXX is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

SELECT
t.[Week], MAX(t.Revenue) AS 'Max Revenue'
FROM
(SELECT
[Week], SUM([Service Total]) AS Revenue
FROM
dbo.['Data - 2017 Appmt Time$']
GROUP BY
[Week]) t;
Error:
Column 't.Week' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
What I'm trying to do is to get the max revenue and the respective week for which is that max revenue. How to make that code working? The code is working if I don't select t.[Week] in the beginning but then I get only the max revenue. If I include t.[Week] in a group by clause, as the message suggests, that I have a list of all revenues week-by-week, but I don't need it. I only need the max revenue and for which week it is.
Apologies if my question is stupid, I'm a beginner in SQL and already lost much time searching for a solution. :( Thanks a lot in advance!
You cannot use a non aggregate column in select which is not part of Group By.
Actually you don't need derived table for this, to find the week with maximum revenue use TOP 1 with Order by
SELECT top 1 [Week],
Revenue = SUM([Service Total])
FROM dbo.['Data - 2017 Appmt Time$']
GROUP BY [Week]
order by Revenue desc
As mentioned by Dan Guzman, if there is a tie in maximum revenue and you want all the tie records then replace TOP 1 with TOP 1 with Ties

SQL Server - select distinct rows and sum of duplicates

I am facing 1 prob in implementing business solution. Any help would be much appreciated.
There is 1 table with 3 columns.
Table Employee
(
Id, Name, Salary
)
Values -
(1,John,10000),
(2,Rey, 15000),
(3,John,20000)
Expected Output -
It should fetch only distinct employees and for duplicate records of employee, it should fetch sum of salary.
So, output should be like this -
(1,john,30000),
(2,Rey,15000)
Please help
Check the basic sintaxis for GROUP BY
SELECT MIN(ID), Name, SUM(Salary)
FROM Employee
GROUP BY Name
The interesting part here is aggregation functions doesnt need to be at the end. As are usually show in the examples

how to calculate all previous datas sum of a sql column on a date range report

I have a crystal report with debit credit columns using a sql command. This report contains a date to date filtering parameters. So the problem is if i filter the report to date range i need all the previous data sum using a sql command.
Select SUM(CAST(debit as DECIMAL(9,2)))- SUM(CAST(credit as DECIMAL(9,2)))
from sum_balance
where sum_date < sum_date
this is my code but i can't get the result from it. (e.g. : if the report starting from 2014-07-01 then i need the sum(debit - credit) of all previous data before 2014-07-01). Can anyone help me to find a solution for this. THe main thing is to add a brought forward balance using sql command on first row. If it is null then it should be 0.00.
Here is your sample table
CREATE TABLE #TEMP(DEBIT NUMERIC(20,2),CREDIT NUMERIC(20,2),DT VARCHAR(20))
INSERT INTO #TEMP
SELECT 1000 DEBIT,500 CREDIT,'2014-11-27' DT
UNION ALL
SELECT 2000 DEBIT,700 CREDIT,'2014-11-28' DT
UNION ALL
SELECT 3000 DEBIT,900 CREDIT,'2014-11-29' DT
I am updating answer for your updated requirement
QUERY 1
This will bring the total till current date, ie, for 2014-11-28 the amount will be (1000+2000)-(500+700), for 2014-11-29 the amount will be (1000+2000+3000)-(500+700+900)
SELECT T2.DEBIT,T2.CREDIT,T2.sum_date,
(SELECT SUM(DEBIT)-SUM(CREDIT) FROM sum_balance WHERE sum_date <= CAST(T2.sum_date AS DATE))
AMOUNT
FROM sum_balance T2
SQL FIDDLE
QUERY 2
This will bring the sum till previous day, that will be opening balance for today's date ie, for 2014-11-29 the amount will be (1000+2000)-(500+700). For easy understanding I have added the previous column also.
;WITH CTE AS
(
SELECT ROW_NUMBER() OVER(ORDER BY CAST(T2.sum_date AS DATE))RNO,
T2.DEBIT,T2.CREDIT,T2.sum_date,
ISNULL((SELECT SUM(DEBIT)-SUM(CREDIT) FROM sum_balance WHERE sum_date <= CAST(T2.sum_date AS DATE)),0)
AMOUNT
FROM sum_balance T2
)
SELECT C1.*,ISNULL(C2.AMOUNT,0) CARRYFORWARD
FROM CTE C1
LEFT JOIN CTE C2 ON C1.RNO=C2.RNO+1
SQL FIDDLE
You can use QUERY 2 and you will get opening balance till previous day in CARRYFORWARD column.
Please leave a message or comment for any changes.
When you need records previous than some date then you need to have that comparision date so that records can be extracted.
Your where clause where sum_date < sum_date won't work this way either you change the right side comparision operator in query or create a parameter in crystal so that user can enter the required end date during run time.
option 1:
E.g: where sum_date < currentdate
option 2:
Create a parameter and declare it in Record Selection Formula in crystal reports so that formed query will be something like
where sum_date < 2014-07-01
You can try this:-
SELECT SUM(CAST(debit as DECIMAL(9,2)))- SUM(CAST(credit as DECIMAL(9,2)))
FROM sum_balance
WHERE sum_date < (Select Max(sum_date) FROM sum_balance)

datediff between multiple records in SQL

I have one scenario where i want to get a count if date difference between the two dates is
<=14 days.That is in first table i have to filter records where any one value of DATE1 values are <=14 days of DATE2.
For Ex:
q1="SELECT DATE1 FROM DATE1_TABLE";
q2="SELECT DATE2 FROM DATE2_TABLE";
My simple query :
SELECT
COUNT(*)
FROM
DATE1_TABLE WHERE DATEDIFF(DD,DATE1,(SELECT DATE2 FROM DATE2_TABLE))<=14
But i have multiple records in both the tables,but i want to choose any record having
this difference then it will get a count >0.So,it is throwing error subquery returned more
than one record.I want some solutions for this.I am using SQL SERVER 2008
NOTE:I can't use join here.because i wanted results from two different queries.
Thanks in advance.
You can use TOP 1 clause in your query..
SELECT TOP 1 *
FROM DATE1_TABLE
WHERE DATEDIFF(DD,DATE1,(SELECT DATE2 FROM DATE2_TABLE))<=14
You cannot use SELECT which will return multiple values where function expects scalar value... however you can join those tables:
SELECT
COUNT(DISTINCT dt1.*)
FROM DATE1_TABLE dt1 INNER JOIN DATE2_TABLE dt2 ON DATEDIFF(DD,DATE1,DATE2)<=14
This query will join tables on values only when they are within 14 days and count on unique values from DATE1_TABLE. I have no idea if is it performance wise.

Resources