how to write a query for this scenario? - sql-server

I had a query like this,
SELECT
CONVERT(VARCHAR(3), DATENAME(MONTH, date)) + '-' +
RIGHT(DATENAME(YEAR, date), 2) AS date
FROM
tblSample
GROUP BY
CONVERT(VARCHAR(3), DATENAME(MONTH, date)) + '-' +
RIGHT(DATENAME(YEAR, date), 2) AS date
ORDER BY
CONVERT(VARCHAR(3), DATENAME(MONTH, date)) + '-' +
RIGHT(DATENAME(YEAR, date), 2) AS date
I had data like this:
Apr-17
jan-16
jan-17
mar-17
I have a requirement that the output should order by year part which means all the '17' (year parts) data should be shown. Like that we have to use order by for year part only how can I do that?

You have to just change your order by query as below, you include both month name and year in order by instead of just select year in order by clause
ORDER BY RIGHT(DATENAME(YEAR, date), 2) AS date
If you wants to apply order on first year and then month then write query as below:
ORDER BY RIGHT(DATENAME(YEAR, [date]), 2) DESC, CONVERT(VARCHAR(3), DATENAME(MONTH, [date]))
I have tried below data:
DECLARE #tblA AS TABLE(
[date] date
)
INSERT INTO #tblA VALUES('01-Apr-2017')
INSERT INTO #tblA VALUES('01-Jan-2016')
INSERT INTO #tblA VALUES('01-Jan-2017')
INSERT INTO #tblA VALUES('01-Mar-2017')
SELECT
CONVERT(VARCHAR(3), DATENAME(MONTH, [date])) + '-' +
RIGHT(DATENAME(YEAR, [date]), 2) AS date
FROM #tblA ORDER BY YEAR([date]) DESC, MONTH([date])
Output:

select CONVERT(VARCHAR(3),DATENAME(MONTH,date))+'-
'+right(DATENAME(YEAR,date),2) as date from
tblSample
order by YEAR([date]),MONTH([date])

select distinct CONVERT(VARCHAR(3),DATENAME(MONTH,date))+'-'+right(DATENAME(‌​
YEAR,date),2) as date,YEAR([date]) as year,MONTH([date]) as month from
tblSample order by YEAR([date]) desc,MONTH([date])

Related

SQL Server Date Calculation

I want to get the based on current date.
If current date is:
01st to 14th of any month, it needs to return 15th of that month
15th to 31st of any month, it needs to return last day of that month
For example:
Current_Date Exp_date
-------------------------
01-08-2019 15-08-2019
10-08-2019 15-08-2019
14-08-2019 15-08-2019
15-08-2019 31-08-2019
20-08-2019 31-08-2019
25-08-2019 31-08-2019
31-08-2019 31-08-2019
I want as much as simplified form.
We can achieve it with simple logic as below .
If You are using Sql Server version 2012 and higher versions we've EOMONTH() Function to give EndOfMonth Date .
Sample Data:
CREATE TABLE #YourTable (CurrentDate DATETIME)
INSERT INTO #YourTable (CurrentDate)SELECT '08-01-2019'
INSERT INTO #YourTable (CurrentDate) SELECT '08-10-2019'
INSERT INTO #YourTable (CurrentDate) SELECT '08-14-2019'
INSERT INTO #YourTable (CurrentDate) SELECT '08-15-2019'
INSERT INTO #YourTable (CurrentDate) SELECT '08-20-2019'
INSERT INTO #YourTable (CurrentDate) SELECT '08-25-2019'
INSERT INTO #YourTable (CurrentDate) SELECT '08-31-2019'
Query:
SELECT DATEPART(DD,CurrentDate),
case when DATEPART(DD,CurrentDate)<15 THEN DATEADD(dd,-day(CurrentDate)+15,CurrentDate)
when DATEPART(DD,CurrentDate)>14 THEN EOMONTH(CurrentDate) END AS Exp_Date
FROM #YourTable
You may try this.
select current_date,
case when datepart(day, current_date) > 14
then
DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, current_date) + 1, 0))
else
DATEADD(D, 15, DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, current_date) , 0)))
end as Exp_date
from yourtable
Try this:replace hardCode date With your date
SELECT CONCAT(CONCAT(CONCAT (CONCAT(CASE WHEN DAY('2017/08/25') < 14 THEN 15 else 31 end , '-'),
CASE WHEN DATEPART(month, '2017/08/25') < 10 THEN Concat('0',DATEPART(month, '2017/08/25')) else DATEPART(month, '2017/08/25') end),'-'), cast(DATEPART(year, '2017/08/25') as nvarchar(4)))
SELECT [Current_date],Exp_date,
CASE WHEN 14 BETWEEN DATEPART(DAY,[Current_date]) AND DATEPART(DAY,Exp_date)
THEN CAST(DATEADD(DAY,15-DATEPART(DAY,[Current_date]),[Current_date]) AS DATE)
ELSE CAST(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,[Current_date])+1,0)) AS DATE)
END
FROM MOnthData
Check this..
select case when datepart(dd, dt) between 1 and 14 then right('0'+ cast(month(dt) as varchar(2)), 2) + '-15-' + cast(year(dt) as varchar(4)) else eomonth(dt) end from test

Group By Month and Year to get distinct month and years then combine as a single date SQL

SELECT CONVERT(DATE,CAST([Year] AS VARCHAR(4))+'-'+
CAST([Month] AS VARCHAR(2))+'-'+
CAST('1' AS VARCHAR(2))) Date
FROM (SELECT YEAR(Date) as [Year], MONTH(Date) as [Month] FROM [dbo].[Data]
GROUP BY YEAR(Date), MONTH(Date)) x
ORDER BY Date DESC
Is there a better way to doinq this with a single query?
The query should return the unique month and year from a table but as combined Date.
IF OBJECT_ID ('tempdb..#TempT') IS NOT NULL DROP TABLE #TempT
CREATE TABLE #TempT(
dt datetime)
INSERT INTO #TempT (dt) VALUES
('2016-10-11'),
('2016-10-3'),
('2016-9-13'),
('2016-9-16')
SELECT DISTINCT CAST(DATEADD(month, DATEDIFF(month, 0, dt), 0) as DATE) AS Dates
from #TempT
Sample data is really a necessity for these kinds of questions, but this function could also be a help for you DATEFROMPARTS
SELECT
DATEFROMPARTS([Year], [Month], 01)
FROM
(
SELECT
YEAR(Date) as [Year],
MONTH(Date) as [Month]
FROM [dbo].[Data]
GROUP BY YEAR(Date), MONTH(Date)
) x
ORDER BY Date DESC
This code takes whatever date you enter and evaluates it as the first of the month. Effectively looking at only month and year:
SELECT
DATEADD(MM,DATEDIFF(MM,0, [Date] ),0) AS [YearMonth]
FROM [dbo].[Data]
ORDER BY
DATEADD(MM,DATEDIFF(MM,0, [Date] ),0)
;

Check order row depending on result query in sql server

I have a table checks2:
AllTaskNo int,
CheckQuosimaNo int,
Masroof numeric(18,3),
Maqbood numeric(18,3),
Date1 smalldatetime
I have a query to get balance:
SELECT
AllTaskNo
,CheckQuosimaNo
,Masroof
,Maqbood
,Date
,(SELECT 0 + SUM(Maqbood - Masroof) AS Expr1
FROM Checks2 AS t2
WHERE (BankNo = 6)
AND (CheckQuosimaNo <= Checks2.CheckQuosimaNo)
AND (Date1 BETWEEN CONVERT(DATETIME, '01/01/2014', 103)
AND CONVERT(DATETIME, '31/10/2015', 103)) AND AllTaskNo
IN (SELECT No
FROM AllTasks
WHERE (BankNo = 6)
AND (Date BETWEEN CONVERT(DATETIME, '01/01/2014', 103)
AND CONVERT(DATETIME, '31/10/2015', 103))))) AS NetAmount
FROM
Checks2
WHERE
(BankNo = 6)
AND
(Date1 BETWEEN CONVERT(DATETIME, '01/01/2014', 103)
AND CONVERT(DATETIME, '31/10/2015', 103))
ORDER BY
BankNo
,Date1
,CheckQuosimaNo
the result is:
enter image description here
I need to make a formula (like excel for example NetAmount = NetAmount before + Maqbood - Masroof)
I expect that the selected row in NetAmount = 656360 but then query produce NetAmount=5567675.976
How can I fix this problem
There are many way to do this like Over and Correlated Sub Queries
Over:
SELECT
AllTaskNo ,Maqbood , Masroof,
SUM(-1*Maqbood +Masroof) OVER (ORDER BY AllTaskNo ) AS NetAmount
FROM Checks2 T1
Correlated Sub Queries (Need Sql server 2014+)
SELECT
AllTaskNo ,Maqbood , Masroof,
(
SELECT
SUM(-1*Maqbood +Masroof)
FROM Checks2 T2
WHERE T2.AllTaskNo <=T1.AllTaskNo
) AS NetAmount FROM Checks2 T1
Feel free to comment if you need any further assistance on this item
I have been solve my problem by my own solution ... I think there is a shorter solution .. but any way I get what I want... My solution is:
1- Make a table (Checks3) with a new field named (rank) which is the correct order of the command result.
2- Create a new command mostly like the first one containing the (bank balance formula).
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Checks3]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[Checks3]
SELECT Checks2.BankNo, Checks2.AllTaskNo, Checks2.CheckQuosimaNo, Checks2.Masroof, Checks2.Maqbood, Checks2.Date1, rank() OVER (ORDER BY checks2.date1, checks2.CheckQuosimaNo) as rank
INTO Checks3
FROM Checks2 INNER JOIN
AllTasks ON Checks2.AllTaskNo = AllTasks.No where Checks2.BankNo =6 and (Checks2.[Date1] BETWEEN CONVERT(DATETIME, '01/10/2015', 103) AND CONVERT(DATETIME,'31/10/2015', 103)) ORDER BY CHECKS2.BankNo, CHECKS2.CheckQuosimaNo
SELECT Checks3.AllTaskNo, Checks3.CheckQuosimaNo, Checks3.Masroof, Checks3.Maqbood, Checks3.Date1,
( SELECT 0+SUM(t2.Maqbood - t2.Masroof) FROM Checks3 t2
WHERE t2.BankNo =6 and t2.rank <= Checks3.rank
and (t2.[Date1] BETWEEN CONVERT(DATETIME, '01/10/2014', 103) AND CONVERT(DATETIME,'31/10/2015', 103))
) as NetAmount
FROM Checks3
where Checks3.BankNo =6 and (Checks3.[Date1] BETWEEN CONVERT(DATETIME, '01/10/2014', 103) AND CONVERT(DATETIME,'31/10/2015', 103)) ORDER BY CHECKS3.RANK

Group By Date and SUM int - Date formatting and Order

I'm trying to get the SUM of the quantity sold on a day. I need the results to be in ORDER BY date. The query below gives me the exact result I need, except the date is not formatted to what I need.
SELECT CAST(Datetime AS DATE) AS 'date', SUM(quantity) as total_quantity
FROM Invoice_Itemized ii
INNER JOIN Invoice_Totals it ON it.Invoice_Number = ii.Invoice_Number
WHERE ii.ItemNum = '4011'
AND it.datetime > '05/15/2015'
GROUP BY CAST(Datetime AS DATE)
SELECT DATENAME(MM, datetime) + ' ' + CAST(DAY(datetime) AS VARCHAR(2)) AS [DD Month], SUM(quantity) as total_quantity
FROM Invoice_Itemized ii
INNER JOIN Invoice_Totals it ON it.Invoice_Number = ii.Invoice_Number
WHERE ii.ItemNum = '4011'
AND it.datetime > '05/15/2015'
GROUP BY DATENAME(MM, datetime) + ' ' + CAST(DAY(datetime) AS VARCHAR(2))
Results for the top query:
2015-05-15 91.43
2015-05-16 84.77
Results for the bottom query:
June 1 128.34
June 10 85.06
The top query gives me the information I need in the order I need it by.
The bottom query gives me the date format I need but in the wrong order.
If you really need to apply different formatting, you can do it using a derived table:
select
DATENAME(MM, [date]) + ' ' + CAST(DAY([date]) AS VARCHAR(2)) AS [DD Month],
total_quantity
from
(
SELECT CAST([Datetime] AS DATE) AS [date], SUM(quantity) as total_quantity
FROM Invoice_Itemized ii
INNER JOIN Invoice_Totals it ON it.Invoice_Number = ii.Invoice_Number
WHERE ii.ItemNum = '4011'
AND it.[datetime] > '05/15/2015'
GROUP BY CAST(Datetime AS DATE)
) as X
This way you can wrap to results into the derived table, and then apply rest of the operations on that.
I would assume this would work too, but can't test now:
SELECT DATENAME(MM, CAST([datetime] AS DATE)) + ' '
+ CAST(DAY(CAST([datetime] AS DATE)) AS VARCHAR(2)) AS [DD Month],
SUM(quantity) as total_quantity
FROM Invoice_Itemized ii
INNER JOIN Invoice_Totals it ON it.Invoice_Number = ii.Invoice_Number
WHERE ii.ItemNum = '4011'
AND it.[datetime] > '05/15/2015'
GROUP BY CAST([datetime] AS DATE)

Select max date from sql server table saved as varchar data in "mm-yyyy" format

In a table date data is saved as mm-yyyy format and its datatype is varchar.
Now I want to retrieve MAX date.
Date is saved in below format and there are thousands of records:
7-1986
10-2012
6-1989
5-1975
7-1974
7-1961
12-1987
10-1975
6-1959
10-2002
12-1991
11-1961
6-1966
12-1959
10-1956
12-1953
6-1999
2-1989
I tried:
SELECT MAX(CONVERT(DATETIME, '1-'+[Date], 105)) As MAXDate FROM tablename
But it returns 2015-12-01 00:00:00.000, but it should be 2015-01-01 00:00:00.000 , because MAX date is saved as 1-2015.
You could try:
SELECT MAX(CAST(RIGHT(Datestring, 4) + RIGHT('00' + SUBSTRING(DateString, 1, CHARINDEX('-', DateString, 1) - 1), 2) + '01' AS SMALLDATETIME)) FROM [YourTable]
SAMPLE:
CREATE TABLE #Dates(DateString VARCHAR(10))
INSERT INTO #Dates VALUES
('7-1986'), ('10-2012'), ('6-1989'),
('5-1975'), ('7-1974'), ('7-1961'),
('12-1987'), ('10-1975'), ('6-1959'),
('10-2002'), ('12-1991'), ('11-1961'),
('6-1966'), ('12-1959'), ('10-1956'),
('12-1953'), ('6-1999'), ('2-1989');
;WITH CTE AS(
SELECT
DateString,
[Month] = SUBSTRING(DateString, 1, CHARINDEX('-', DateString, 1) - 1),
[Year] = RIGHT(Datestring, 4),
[Date] = CAST(RIGHT(Datestring, 4) + RIGHT('00' + SUBSTRING(DateString, 1, CHARINDEX('-', DateString, 1) - 1), 2) + '01' AS SMALLDATETIME)
FROM #Dates
)
SELECT MAX([Date]) AS MaxDate FROM CTE
DATA
DateString
----------
7-1986
10-2012
6-1989
5-1975
7-1974
7-1961
12-1987
10-1975
6-1959
10-2002
12-1991
11-1961
6-1966
12-1959
10-1956
12-1953
6-1999
2-1989
RESULT
MaxDate
-----------------------
2012-10-01 00:00:00
You can try.
SELECT Max(cast('1-'+Date as DateTime)) As MAXDate FROM tablename
You can use STUFF function to add -1:
SELECT MAX(CONVERT(DATETIME, STUFF([Date], CHARINDEX('-', [Date]), 0, '-1'), 121))

Resources