Why this sql returns like that? - sql

i have below sql
SELECT SUM(amount) from CustomerPayment where date like '%2013' GROUP BY TYPE
in Type column there are two choice one them is BANK and the other one is CASH
I want to sum these seperately. For ex: bank is totally 500 and cash is 400
However above sql does not sum the records. Instead, it returns first record of bank and cash records. Why?

I would say try and add type to the sql query. Then it has a visible representation of the type you wish to group by.
SELECT SUM(amount), TYPE from CustomerPayment where date like '%2013' GROUP BY TYPE

can you try using year(date)=2013, as data is not there so I am guessing if 'like' function is not letting group by to perform its functionality properly.

If your date field has a datatype of Date or DateTime then the LIKE operator won't work.
For date comparisons use date functions.
SELECT SUM(amount)
FROM CustomerPayment
WHERE YEAR(date) = 2013
GROUP BY TYPE
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_year

include TYPE col also
SELECT TYPE, SUM(amount) from CustomerPayment where date like '%2013' GROUP BY TYPE

Related

SQL max without group by

I would like to get one row with the maximum date. I cannot use group by as I need to retrieve all data in that row.
I have this:
ID Date Country
1 05/05/2019 US
2 05/06/2019 UK
I want to get this:
ID Date Country
2 05/06/2019 UK
I've tried the below but it didn't work for me
select TOP 1 ID, Date, country
from table
order by Date desc
I don't believe you. Here is a db<>fiddle that shows three different interpretations of the date in your sample data:
as a string
as mm/dd/yyyy
as dd/mm/yyyy
All three of them produce the same result.
I suspect that your actual data is more complicated and you have oversimplified the example for the question. Further, my suspicion is that the date column is stored as a string rather than a date.
As a string, you might have some hidden characters that affect the sorting (such as leading spaces).
If this is the case, fix the data type and your code will work.
This depends on what DB system you are using.
In Microsoft SQL server, you can use row_number() function:
select top 1 *
from facts
order by ROW_NUMBER() over (order by dateKey)
Can you try this?
select Top 1 ID,Date, country from table where date = max(date)
First set the DATE or DATETIME Datatype in your [Date] column
then try this code:
SELECT TOP 1 ID, [Date] , country FROM TableName ORDER BY Date DESC
SELECT ID,Date,Country from TableName Where Date = MAX(Date) AND Rownum <= 1

sql count function with subquery

here is my query
select narr,vocno,count(*)
from KontenLedger
WHERE VOCDT>'2018-07-01'
group by narr,vocno
having count(*)<'3'
actually if i wright as i given above ,the result which calculates two fields ('narr' and 'vocno') if i remove the field ('narr') answer is correct. i need to view the field 'narr' also without counting
Without knowing your database, nor having some limited sample date, nor expected output?
SELECT
vocno,
COUNT(*) AS total,
MAX(narr) AS max_narr
FROM KontenLedger
WHERE vocdt > '2018-07-01'
GROUP BY vocno
HAVING COUNT(*) < 3

Date - Data type mismatch in criteria expression in Access

I have a table which stores birthdate in the field DateValueOf. I am creating a query where user can input any date and the query will return customers which have birthday on that day.
For this, I am trying to convert all the year in DateValueOf to current year.
eg > #13-10-1996# to #13-10-2016#
eg > #13-10-2001# to #13-10-2016#
So that I will then ask user to select date from date picker and run the below query.
SELECT CustomerID
WHERE FormatDateTime(DateValue(DateSerial(Year(Date()),Month([DateValueOf]),Day([DateValueOf]))),2) >= #13-10-2016#
But this SQL statement produces an error data type mismatch in criteria expression
Please highlight my mistake. Thanks in advance. I am also open to any other way to get who's birthday it is today.
Assuming you receive the date from a date picker Control (call it: myDatePicker), today's date, returned by function Date() is not relevant.
And unless you want the age, Year() is not relevant either.
SELECT CustomerID
FROM MyTableName
WHERE Month(myDatePicker) = Month([DateValueOf]) AND Day([DateValueOf]) = Day([myDatePicker])
If you want the customer's age at this birthday, you can add the calculation to the SELECT clause:
SELECT CustomerID, Year(myDatePicker) - Year(DateValueOf) As CustomerAge
FROM MyTableName
WHERE Month(myDatePicker) = Month([DateValueOf]) AND Day([DateValueOf]) Day([myDatePicker])
Don't worry about formatting the date, just use a date comparison:
SELECT CustomerID
WHERE DateSerial(Year(Date()),Month([DateValueOf]),Day([DateValueOf]))
>= #13-10-2016#

how make query about some of a field are equal?

I'm trying the code below
SELECT Sum(Price) FROM Faktor WHERE date=date
but it shows total of all price. I want to show the sum of per day like:
date ----- sum
2015/5/1 12345
2015/5/2 54124
I have tried below code too but get error:
SELECT date,Sum(Price) FROM Faktor WHERE date=date
[Err] 42000 - [SQL Server]Column 'Faktor.date' is invalid in the
select list because it is not contained in either an aggregate
function or the GROUP BY clause.
Try
SELECT [date],SUM([Price])
FROM Faktor
GROUP BY [date]
Not sure why you'd use date=date, so I left it out.
Just as the error message tells you, you need to use a group by clause and the date column needs to be in it.
SELECT date, SUM(Price)
FROM Faktor
WHERE date=date -- this looks a bit odd... maybe you want a range of dates or something?
GROUP BY date
With SQL Server all non-aggregated columns from the select statement needs to be grouped (unlike some versions of MySQL for instance).
SELECT
date
,SUM(Price)
FROM
Faktor
WHERE
--add date rules here if you have date criteria i.e. date >= 'someDate'
GROUP BY
date

Group by in t-sql not displaying single result

See the image below. I have a table, tbl_AccountTransaction in which I have 10 rows. The lower most table having columsn AccountTransactionId, AgreementId an so on. Now what i want is to get a single row, that is sum of all amount of the agreement id. Say here I have agreement id =23 but when I ran my query its giving me two rows instead of single column, since there is nano or microsecond difference in between the time of insertion.
So i need a way that will give me row 1550 | 23 | 2011-03-21
Update
I have update my query to this
SELECT Sum(Amount) as Amount,AgreementID, StatementDate
FROM tbl_AccountTranscation
Where TranscationDate is null
GROUP BY AgreementID,Convert(date,StatementDate,101)
but still getting the same error
Msg 8120, Level 16, State 1, Line 1
Column 'tbl_AccountTranscation.StatementDate' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Your group by clause is in error
group by agreementid, convert(date,statementdate,101)
This makes it group by the date (without time) of the statementdate column. Whereas the original is grouping by the statementdate (including time) then for each row of the output, applying the stripping of time information.
To be clear, you weren't supposed to change the SELECT clause
SELECT Sum(Amount) as Amount,AgreementID, Convert(date,StatementDate,101)
FROM tbl_AccountTranscation
Where TranscationDate is null
GROUP BY AgreementID,Convert(date,StatementDate,101)
Because you have a Group By StatementDate.
In your example you have 2 StatementDates:
2011-03-21 14:38:59.470
2011-03-21 14:38:59.487
Change your query in the Group by section instead of StatementDate to be:
Convert(Date, StatementDate, 101)
Have you tried to
Group by (Convert(date,...)
instead of the StatementDate
You are close. You need to combine your two approaches. This should do it:
SELECT Sum(Amount) as Amount,AgreementID, Convert(date,StatementDate,101)
FROM tbl_AccountTranscation
Where TranscationDate is null
GROUP BY AgreementID,Convert(date,StatementDate,101)
If you never need the time, the perhaps you need to change the datatype, so you don't have to do alot of unnecessary converting in most queries. SQL Server 2008 has a date datatype that doesn't include the time. In earlier versions you could add an additional date column that is automatically generated to strip out the time companent so all the dates are like the format of '2011-01-01 00:00:00:000' then you can do date comparisons directly having only had to do the conversion once. This would allow you to have both the actual datetime and just the date.
You should group by DATEPART(..., StatementDate)
Ref: http://msdn.microsoft.com/en-us/library/ms174420.aspx