Please help me with the group by clause - sql

USE [MAS_CAN]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spHistorybyCalenderYear]--create a stored proc
#Year int = '2013'
AS
Begin
SET NOCOUNT ON
SELECT
isnull(round(l.UnitPrice*l.QuantityShipped,2),0) as SalesAmount,
isnull(round(l.unitCost*l.QuantityShipped,2),0) as CostAmount,
(case
when month(h.INVOICEDATE)=01 then '01'
when month(h.INVOICEDATE)=02 then '02'
when month(h.INVOICEDATE)=03 then '03'
when month(h.INVOICEDATE)=04 then '04'
when month(h.INVOICEDATE)=05 then '05'
when month(h.INVOICEDATE)=06 then '06'
when month(h.INVOICEDATE)=07 then '07'
when month(h.INVOICEDATE)=08 then '08'
when month(h.INVOICEDATE)=09 then '09'
when month(h.INVOICEDATE)=10 then '10'
when month(h.INVOICEDATE)=11 then '11'
when month(h.INVOICEDATE)=12 then '12'
END) as Period
FROM AR_INVOICEHISTORYHEADER h join AR_INVOICEHISTORYDETAIL l on (h.INVOICENO = l.INVOICENO)
Group by l.unitprice,l.unitcost,l.quantityShipped,h.invoicedate
order by Period
END
I would like to group it by period...Say I would like to see
Period SalesAmount CostAmount
01 22 19
02 24 25

Use this:
GROUP BY l.unitprice, l.unitcost, l.quantityShipped, CAST(MONTH(h.invoicedate) as varchar)
Also, you can get rid of that large case statement if you use this in its place:
SELECT
isnull(round(l.UnitPrice*l.QuantityShipped,2),0) as SalesAmount,
isnull(round(l.unitCost*l.QuantityShipped,2),0) as CostAmount,
CAST(MONTH(h.invoicedate) as varchar) as Period
FROM ...
As #Kaf mentioned, if you want Period to be 0 padded you can use either of these instead of the direct CAST:
right(100 + month(h.invoicedate),2)
left(convert(varchar, h.invoicedate, 10), 2)

Related

Strange (Cisco) datetime string to SQL datetime

Trying to import a rather unusual formatted datetime sting in SQL.
The Source is an automated export from a Cisco networking-system, I can't alter it's formatting.
The format is Sun Dec 02 03:59:54 CET 2018
Tried datetimefromparts(), convert() combined with substring()'s
CREATE FUNCTION [dbo].[Cisco2dateTime]
( #CDate varchar(28)) RETURNS datetime
AS
BEGIN
RETURN ( datetimefromparts(
right(#CDate,4),
case substring(#CDate,5,3) when 'Jan' then '01' when 'Feb' then '02' when 'Mar' then '03' when 'Apr' then '04' when 'May' then '05' when 'Jun' then '06' when 'Jul' then '07' when 'Aug' then '08' when 'Sep' then '09' when 'Okt' then '10' when 'Nov' then '11' when 'Dec' then '12' END,
substring(#CDate,9,2),
substring(#CDate,12,2),
substring(#CDate,15,2),
substring(#CDate,18,2),0) )
END
GO
}
Any idea's how to do this more efficient?
If the incoming format is consistent, you can shrink it down to something like this:
DECLARE #time NVARCHAR(28) = 'Sun Dec 02 03:59:54 CET 2018'
SELECT CAST(SUBSTRING(#time,4,17) + RIGHT(#time,4) AS DATETIME)
Returns 2018-12-02 03:59:54.000
Edited for #Clockwork-Muse
If you want to include the timezone information, you can use a timezone table to match the abbreviations or, if you only have a handful of potential timezones, you can use a table value constructor like in the new example which will return a timezoneoffset:
DECLARE #time NVARCHAR(30) = 'Sun Dec 02 03:59:54 CET 2018'
SELECT TODATETIMEOFFSET(CAST(SUBSTRING(#time,4,17) + RIGHT(#time,4) AS DATETIME), z.TZOffset)
FROM
(
VALUES ('CET','+01:00'),('AST','+03:00'),('NZDT','+13:00')
)AS z(TZName, TZOffset)
WHERE #time LIKE '%'+z.TZName+'%'

Convert YYYYMM to MMMYY

I have a period 201604 (nvarchar). Is there a way that I can convert 201604 to APR16?
Use the DATENAME & SUBSTRING functions, like this:
declare #str nvarchar(50) = '201604'
select UPPER(left(datename(mm,cast(#str+'01' as date)),3))+substring(#str,3,2) --APR16
It is a bit ugly, but you can't use any of the built-in date formatting stuff as is. Feel free to swap out the case statement for a join if you have a month names table, etc.:
DECLARE #exampleVal NVARCHAR(6) = '201604';
SELECT CASE SUBSTRING(#exampleVal, 5, 2)
WHEN '01' THEN 'JAN'
WHEN '02' THEN 'FEB'
WHEN '03' THEN 'MAR'
WHEN '04' THEN 'APR'
WHEN '05' THEN 'MAY'
WHEN '06' THEN 'JUN'
WHEN '07' THEN 'JUL'
WHEN '08' THEN 'AUG'
WHEN '09' THEN 'SEP'
WHEN '10' THEN 'OCT'
WHEN '11' THEN 'NOV'
WHEN '12' THEN 'DEC'
END +
SUBSTRING(#exampleVal, 3, 2)
Try this:
Add '01' (as first day of month), so convert your varchar to datetime and get the datename of the month:
declare #myperiod nvarchar(10)
SET #myperiod = '201604'
SET #myperiod = #myperiod + '01'
SELECT UPPER(SUBSTRING(DATENAME(month, CONVERT(datetime, #myperiod)), 1, 3)) +
SUBSTRING(CONVERT(varchar, DATEPART(year, CONVERT(datetime, #myperiod))), 3, 4)
Add 01 at the last, so that it changes to a valid date format. Then use the datename function:
DECLARE #STRING VARCHAR(10)='201604'
SELECT DATENAME(MONTH,#STRING+'01') +' '+SUBSTRING(#STRING,3,2)
Output:
April 16
In two lines:
declare #napis varchar(6)='201506'
SELECT UPPER(LEFT(DATENAME(month, #napis+'01'),3)) + SubString(#napis,3,2)
Another option is by using Format() and DateFromParts(). This will work in SQL Server 2012 or newer versions:
Declare #Period NVarchar (6) = N'201604'
Declare #Format NVarchar (5) = N'MMMyy'
Select Upper(Format(DateFromParts(Left(#Period, 4), Right(#Period, 2), 1), #Format))
APR16
Use simple this
declare #test nvarchar(max) = '201604'
select left(DATENAME(month, #test +'01'),3) + SubString(#napis,3,2)
Another way:
DECLARE #Date varchar(6) = '201604'
SELECT REPLACE(SUBSTRING(CONVERT(char(9), CAST(#Date +'01' as Date), 6), 4, 7), ' ', '')
Try this one..
DECLARE #DATE NVARCHAR(6) = '201604'
SELECT datename(MONTH,CONVERT(DATE,CONVERT(DATE,LEFT(#DATE,4)+'.'+RIGHT(#DATE,2)+'.01',102),102))

SQL convert quarter date number to string padding 0s as prefix for numbers < 10

I want to convert monthly_dates to quarter, but I'd like to path single digit numbers with 0s.
I.e.,
monthly_date = '2015-01-01'
In the SQL query I do:
QUARTER(monthly_date)*3-2 AS varchar
but that gives me '1' instead of '01'
Is there a way to make it give me '01', '04', '07' and '10'?
Can you have quarter number bigger than 4?
Anyhow... you can pad numbers the way you want (be sure to check SQL Reference Manual > SQL Functions > Formatting Functions).
For example:
SQL> select to_char( 4 , '09' ) ;
to_char
---------
04
SQL> select to_char( 12 , '09' ) ;
to_char
---------
12
I admit, this is a brute force method but I have used it in the past.
Given these 4 variables, I can calculate the StartCalendarId with padded 0's
Declare #StartDate date
Declare #StartYear int
Declare #StartMonth int
Declare #StartDay int
Set #StartYear = Year(#StartDate)
Set #StartMonth = Month(#StartDate)
Set #StartDay = Day(#StartDate)
Set #StartCalendarId =
(CONVERT([int],
(((CONVERT([varchar](4),#StartYear)+
case when len(#StartMonth)=(1) then '0' else '' end)+
CONVERT([varchar](2),#StartMonth))+
case when len(#StartDay)=(1) then '0' else '' end)
+CONVERT([varchar](2),#StartDay))
)

Sql Datetime convert

In a database table, I have two column storing date and time in this format:
D30DAT D30TIM
140224 75700
I need update a new field where store date in the format
2014-02-24 07:57:00.000
How I can use a SQL query to do it?
For Postgres and Oracle (assuming those columns are varchar):
select to_timestamp(dt, 'yymmdd hh24miss')
from (
select d30dat||' '||case when length(d30tim) = 5 then '0'||d30tim else d30tim end as dt
from x
) t;
The case expression adds a leading 0 if the time part only consists of 5 digits so that the format mask can be specified with always 2 digits for the hour. The blank between the two columns is essentially only a debugging aid and could be left out.
The result is a real timestamp value that can easily be formatted using to_char() to the desired format.
SQLFiddle for Postgres: http://sqlfiddle.com/#!15/ac07a/2
SQLFiddle for Oracle: http://sqlfiddle.com/#!4/ac07a2/4
Try this function. Its not particularly fast or great, but converts the fields you specified.
CREATE FUNCTION GetDateTimeFromINT
(
#Date INT,
#Time INT
)
RETURNS DATETIME
AS
BEGIN
DECLARE #YearNo VARCHAR(4)
DECLARE #MonthNo VARCHAR(3)
DECLARE #DayNo VARCHAR(2)
DECLARE #HourNo VARCHAR(2)
DECLARE #MinNo VARCHAR(2)
DECLARE #SecNo VARCHAR(2)
SET #YearNo = LEFT(CONVERT(VARCHAR,#Date), LEN(#Date)-4)
SET #MonthNo = SUBSTRING(CONVERT(VARCHAR,#Date),LEN(#Date)-3,2)
SET #DayNo = SUBSTRING(CONVERT(VARCHAR,#Date),LEN(#Date)-1,2)
SET #HourNo = LEFT(CONVERT(VARCHAR,#Time), LEN(#Time)-4)
SET #MinNo = SUBSTRING(CONVERT(VARCHAR,#Time),LEN(#Time)-3,2)
SET #SecNo = SUBSTRING(CONVERT(VARCHAR,#Time),LEN(#Time)-1,2)
SET #YearNo = '20' + #YearNo
IF LEN(#HourNo) = 1
BEGIN
SET #HourNo = '0' + #HourNo
END
SET #MonthNo = CASE
WHEN #MonthNo = '01' THEN 'JAN'
WHEN #MonthNo = '02' THEN 'FEB'
WHEN #MonthNo = '03' THEN 'MAR'
WHEN #MonthNo = '04' THEN 'APR'
WHEN #MonthNo = '05' THEN 'MAY'
WHEN #MonthNo = '06' THEN 'JUN'
WHEN #MonthNo = '07' THEN 'JUL'
WHEN #MonthNo = '08' THEN 'AUG'
WHEN #MonthNo = '09' THEN 'SEP'
WHEN #MonthNo = '10' THEN 'OCT'
WHEN #MonthNo = '11' THEN 'NOV'
WHEN #MonthNo = '12' THEN 'DEC'
END
RETURN CONVERT(DATETIME, #DayNo + '-' + #MonthNo + '-' + #YearNo +' ' + #HourNo + ':' + #MinNo + ':' + #SecNo)
END
GO
Call it like so:
SELECT *, dbo.GetDateTimeFromINT(D30DAT,T30DAT) OutputDT
FROM SourceTable
If you need help with the update statement, let me know
Because someone gave a convoluted answer in SQL Server, I want to point out that there is a much simpler way.
I also want to point out that the format is not unreasonable. It provides easy access to the date parts and it is sortable. Of course, a real date/time value has these properties as well; I am guessing that this is some legacy format from some ancient system.
In any case, try this:
with t as (select 140224 as ymd, 75700 as hms)
select cast(cast(ymd as varchar(255)) + ' ' +
stuff(stuff(right('000000' + cast(hms as varchar(255)), 6
), 3, 0, ':'
), 6, 0, ':')
from t;
This turns the numbers into the format YYMMDD HH:MM:SS which SQL Server recognizes as a date/time value. Actually it would be better to pre-pend "20" for the four-digit year, but I'm not sure what the OP wants in terms of Y2K convertibility.
Although the code would look a bit different, similar logic would work in most databases.

Comparing Dates in a specific format in SQL Server

I have a column called "Mon-YY" (varchar(n) data type) in one of my tables which has values like:
Aug-12
Sep-12
Oct-12
Nov-12
Dec-12
Jan-13
Feb-13
Mar-13
Apr-13
May-13
Jun-13
I want to compare these values and retrieve the records from the table based on the date range specified.
I am assuming I'd need to convert the above values into DATE format. But I'm not sure then how do I keep track of days too.
You can use the DATEPART function, but you need to do it on a full date:
SELECT DATEPART(MM, 'Aug-12') --> error
SELECT DATEPART(MM', 01-Aug-12') --> 8
So try something like this:
SELECT
DATEPART(MM, CONCAT('01-', [Mon-YY])) AS TheMonth,
DATEPART(YYYY, CONCAT('01-', [Mon-YY])) AS TheYear
FROM myTable
ORDER BY TheYear, TheMonth
SELECT CONVERT (date, REPLACE (MyColumn, '-', ' 01 '))
FROM MyTable
Something like this should give you a date. It will always be the first of the month. You can use the expression in a WHERE clause with <, >, or BETWEEN. I don't know why you would need to keep track of them.
I used cast
-- example table and data
DECLARE #table table
(
[Mon-YY] varchar(20)
)
insert into #table values ('Aug-12')
insert into #table values ('Sep-12')
insert into #table values ('Oct-12')
insert into #table values ('Nov-12')
insert into #table values ('Dec-12')
insert into #table values ('Jan-13')
insert into #table values ('Feb-13')
insert into #table values ('Mar-13')
insert into #table values ('Apr-13')
insert into #table values ('May-13')
insert into #table values ('Jun-13')
select cast('01-' + [Mon-YY] as Date)
from #table
To convert these values to date you should use:
SELECT CONVERT(VARCHAR(20), '01 ' + [Mon-YY], 6) as BeginOfInterval
To get the last day of a month, you should use (look here):
SELECT DATEADD(s,-1,DATEADD(mm,
DATEDIFF(m,0,CONVERT(VARCHAR(20), '01 ' + [Mon-YY], 6))+1,0)) as EndOfInterval
Then you could use this two queries to get the first and last dates of interval.
A solution is to transform your column in something easier to sort like a number.
Bellow I transform the column in the full year followed by the month (numeric index 1 to 12) but this is used only in order by clause.
select *
from theTable
--where ???
order by case when right([mon-yy],2) <= 70 then '19' else '20' end +
right([mon-yy],2) +
case left([mon-yy],3)
when 'Jan' then '01'
when 'Feb' then '02'
when 'Mar' then '03'
when 'Apr' then '04'
when 'May' then '05'
when 'Jun' then '06'
when 'Jul' then '07'
when 'Aug' then '08'
when 'Sep' then '09'
when 'Oct' then '10'
when 'Nov' then '11'
when 'Dec' then '12'
end