how to use convert and datepart at the same time - sql-server

I have here a select command which is used in my crystal report:
SELECT cfvgl.v_id, operator.o_id, cfvgl.cfvgl_no, operator.owner_name,
operator.business_address, vessel_details.ship_name, payment.or_number ,
payment .date_paid , payment.amount , signature.data,
cfvgl.cfvgl_date_released, DATEPART(day, cfvgl.cfvgl_validity_start) as day_issued,
DATEPART(month, cfvgl.cfvgl_validity_start) as month_issued,
DATEPART(year, cfvgl.cfvgl_validity_start) as year,
gear.bag_bunt_mesh_size, gear.body_mesh_size, gear.wing_mesh_size,
cfvgl.catcher_type, cfvgl.other_gear, gear.stretched_depth,
gear.finished_depth, gear.mesh_size, gear.finished_length,
gear.finished_width, gear.total_length, gear.cod_end_mesh_size,
gear.otter_board_size, gear.towing_rope_length, gear.tomweight,
gear.bouyline_length, gear.branchline_length, gear.branchline_distance,
gear.hook_number, gear.hook_type, gear.hook_size, gear.bait_type,
gear.hook_total_number, gear.target_species, gear.mainline_length,
gear.swivel_size, gear.wire_leader_length, gear.netting_type
FROM cfvgl INNER JOIN
vessel_details ON vessel_details.v_id = cfvgl.v_id INNER JOIN
operator ON vessel_details.o_id = operator.o_id LEFT OUTER JOIN
applications ON vessel_details.v_id = applications.v_id LEFT OUTER JOIN
payment ON payment.app_no = applications.app_no LEFT OUTER JOIN
gear ON gear.v_id = vessel_details.v_id LEFT OUTER JOIN
signature ON signature.signature_id = cfvgl.signature_id
my problem is , i have to convert and display the return date of the datepart(month) as words, for example 1 = january ..
i only datepart the month ,
DATEPART(month, cfvgl.cfvgl_validity_start) as month_issued
how will i able to change the format of the datepart month to words?
thanks.

Use DATENAME to get the name.
DATENAME(month, cfvgl.cfvgl_validity_start) as month_issued

Use the DATENAME function to get the month in words like so:
SELECT DATENAME(month, cfvgl.cfvgl_validity_start) AS month_issued
FROM yourtable

Related

Convert Access Crosstab Query to SQL Server

I have a crosstab query in MS Access which runs very slow after migrating my backend to an SQL Server 2017. So I want to create a view in SQL that does the same aggregation.
MS Access Query:
TRANSFORM Sum([Auftrag Positionen].Gesamtpreis) AS SummevonGesamtpreis
SELECT Format$([Stammdaten Datum].[Datum],'yyyy\/mm mmmm') AS Monat, Sum([Auftrag Positionen].Gesamtpreis) AS Gesamt
FROM [Stammdaten Datum] LEFT JOIN (Auftrag LEFT JOIN ([Stammdaten Statistik] RIGHT JOIN [Auftrag Positionen] ON [Stammdaten Statistik].Kennzeichen = [Auftrag Positionen].Statistik) ON Auftrag.[Auftrags-Nummer] = [Auftrag Positionen].[Auftrags-Nummer]) ON [Stammdaten Datum].Datum = Auftrag.Auftragseingang
WHERE (((Auftrag.[Auftrag-Angebot])="Auftrag"))
GROUP BY Format$([Stammdaten Datum].[Datum],'yyyy\/mm mmmm')
ORDER BY Format$([Stammdaten Datum].[Datum],'yyyy\/mm mmmm') DESC
PIVOT [Stammdaten Statistik].Beschreibung;
I get that I can cancel out the access date formatting:
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, [Stammdaten Datum].[Datum]), 0) AS Monat, Sum([Auftrag Positionen].Gesamtpreis) AS Gesamt
FROM [ROBI_1].[dbo].[Stammdaten Datum] LEFT JOIN ([ROBI_1].[dbo].Auftrag LEFT JOIN (ROBI_1.dbo.[Stammdaten Statistik] RIGHT JOIN ROBI_1.dbo.[Auftrag Positionen] ON [Stammdaten Statistik].Kennzeichen = [Auftrag Positionen].Statistik) ON Auftrag.[Auftrags-Nummer] = [Auftrag Positionen].[Auftrags-Nummer]) ON [ROBI_1].[dbo].[Stammdaten Datum].Datum = Auftrag.Auftragseingang
WHERE ((([Auftrag].[Auftrag-Angebot])='Auftrag'))
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, [Stammdaten Datum].[Datum]), 0)
ORDER BY DATEADD(MONTH, DATEDIFF(MONTH, 0, [Stammdaten Datum].[Datum]), 0) DESC
But I don't know how to do the pivot aggregation, everything I've tried gave me syntax errors. (I am a noob in SQL/T-SQL indeed).
I appreciate any help!
I guess it would be something like this:
;WITH MonatGesamt AS
(
SELECT
Monat = DATEPART(MONTH, SD.Datum)
, Gesamtpreis = ISNULL(AP.Gesamtpreis, 0)
FROM ROBI_1.dbo.[Stammdaten Datum] SD
LEFT JOIN ROBI_1.dbo.Auftrag AT ON AT.Auftragseingang = SD.Datum
LEFT JOIN ROBI_1.dbo.[Auftrag Positionen] AP ON AP.[Auftrags-Nummer] = AT.[Auftrags-Nummer]
WHERE AT.[Auftrag-Angebot] = 'Auftrag'
)
SELECT
Monat
, Gesamt = SUM(Gesamtpreis)
FROM MonatGesamt
GROUP BY Monat
ORDER BY Monat DESC

Update Column using calculation in last year from another table

I am trying to update (using Inner joins for three tables) item stats STAT for table IM_ITEM by highlighting items that sold less than 12 as "D" (Discontinue).
The 2nd table PS_TKT_HIST_LIN has the Quantity sold column QTY_SOLD for each item on each day and the date column BUS_DAT.
I also need a third table IM_INV to filter the data, I need to say the last received date LST_RECV_DAT for these items is earlier than "2019-01-01" and last sales date LST_SAL_DAT is after "2019-01-01". I used the following code
UPDATE M
SET M.STAT = 'D'
FROM
dbo.IM_ITEM AS M
INNER JOIN
IM_INV AS N
ON
M.ITEM_NO = N.ITEM_NO
INNER JOIN
dbo.PS_TKT_HIST_LIN S`
ON
M.ITEM_NO = S.ITEM_NO
WHERE
CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, N.LST_RECV_DAT))) <= '2019-01-01'
AND CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, N.LST_SAL_DAT))) >= '2019-01-01'
AND M.STAT = 'A'
AND SUM(case when DATEPART(YYYY, (BUS_DAT)) = DATEPART(YYYY, DATEADD(YYYY, -1, getdate()))
AND DATEPART(yyyy, (BUS_DAT)) = DATEPART(yyyy, DATEADD(YYYY, -1, getdate()))
then qty_sold else 0)<12
It comes with an error
Any advise please
You should use HAVING clause instead of Sum in where.
You can use CTE to achieve the value, then update accordingly.
;with cte as(
select ITEM_NO, ..
from ..
group by ITEM_NO
having .. < 12
)
update M
set SET M.STAT = 'D'
from dbo.IM_ITEM AS M
inner join cte on M.ITEM_NO = cte.ITEM_NO
You can't use an aggregate function in where clause unless defined under subquery.

Find out Monthly Percentage in SQL

I am trying to find out monthly percentage (last 12 Months) for the below query
with severity wise, it would be great if anyone could help me out
SELECT Month(a.[Work Initated Date]) AS Month, a.[Initial Severity],
(CAST(Count(a.[Case Number]) AS Decimal(10,1))/ (select CAST(Count(a.[Case Number]) AS Decimal(10,1))
FROM [DSTRINING].[dbo].[SFDC WorkInitiated] (nolock) a
where a.[Initial Severity]='Critical' AND Month(a.[Work Initated Date])=Month(getdate()))*100) AS 'Work Initated%'
FROM [DSTRINING].[dbo].[SFDC WorkInitiated] (nolock) a
where a.[Initial Severity]='Critical' AND Month(a.[Work Initated Date])=Month(getdate()) AND a.[Work Initiated Target Breached]='NO'
Group by Month(a.[Work Initated Date]), a.[Initial Severity]
You can use window functions for this. Your query is a bit hard to follow, but . . .
select Year(wi.[Work Initated Date]) AS yyyy, Month(wi.[Work Initated Date]) AS mm,
wi.[Initial Severity],
count(*) * 100.0/ sum(count(*)) over partition by Year(wi.[Work Initated Date]), Month(wi.[Work Initated Date])) as [Work Initated%]
from [DSTRINING].[dbo].[SFDC WorkInitiated] wi
where wi.[Initial Severity] = 'Critical' and
Month(wi.[Work Initated Date]) = Month(getdate())) and
wi.[Work Initiated Target Breached] = 'NO'
Group by Year(wi.[Work Initated Date]), Month(wi.[Work Initated Date]), wi.[Initial Severity];
Notes:
I included the year along with the month. I just think that is a good practice to avoid unwanted errors.
I changed the table alias to the initials of the table. That makes the query easier to follow.
The window function in the select calculates the ratio you want.
I removed the conversion to decimal(10, 1). I think that confuses the query (although you can add it back in for your output purposes).

15 days before today in SQL Server

I am trying to find the list of specific job # from load date in our database with the specific condition and I have to use inner join as well.
i want to have last 15 days worth of Job # in my store procedure.
How do I set up the LoadDate that will change auto for last 15 days only.
Here is my query:
select pr.Job_Number,
Count(ItemCode1) as [Total Records],
si.PackageComplete
from
processed_record pr
inner join scanner_2 si on pr.ItemCode1 = si.ItemCode1
where
pr.Format_Name like '%Lin%' and pr.LoadDate >= '03/01/2016'
group by
pr.Job_Number, si.PackageComplete
order by
si.PackageComplete, pr.Job_Number
Your query should be as follow:
select pr.Job_Number,
Count(ItemCode1) as [Total Records],
si.PackageComplete
from
processed_record pr
inner join scanner_2 si on pr.ItemCode1 = si.ItemCode1
where
pr.Format_Name like '%Lin%' and pr.LoadDate >= DATEADD(DAY,-15,GETDATE())
group by
pr.Job_Number, si.PackageComplete
order by
si.PackageComplete, pr.Job_Number
GETDATE() will get the current date and DATEADD() function will add (subtract) -15 days.
You could use
CONVERT(date, DATEADD(DAY, -15, GETDATE()))
insted your fix Date Value.
With this code you recieve the current Date GetDate() and substract 15 Days DateAdd(day, -15, DateValue)
Finaly you Convert it into Date Typ Convert(date, value) otherwise you would get the current time, too.

in grouping getting duplicate records

I want to filter records on the basis of month. Requirement is in month how much projects are in "completed, pending, started etc" status. This is my query but i am getting duplicate records.
SELECT distinct
convert(varchar(7), w.ExpectedStartDate, 126) AS StatusOfMonth,
COUNT(w.StatusTypeId) AS StatusCount,
w.StatusTypeId,
st.StatusTypeName
FROM Table1 w
LEFT OUTER JOIN StatusType st ON st.StatusTypeId = w.StatusTypeId
WHERE CONVERT(VARCHAR(20), w.ExpectedStartDate, 103) BETWEEN '10/01/2011' AND '14/04/2011'
GROUP BY ExpectedStartDate, w.StatusTypeId, st.StatusTypeName
Please see image to clarify what i want. Please let me know how can i get correct results.
Looks like your grouping by the date, not by the month or by the status of month
Group by
DATEPART(M, ExpectedStartDate)
or
convert(varchar(7), w.ExpectedStartDate, 126)
instead of just ExpectedStartDate
EDIT
In response the comment:
Try getting rid of
convert(varchar(7), w.ExpectedStartDate, 126) AS StatusOfMonth
and just try it like this:
SELECT
convert(varchar, datepart(yyyy, w.ExpectedStartDate)) + '-' + CONVERT(varchar(3), DATENAME(month, w.ExpectedStartDate)),
w.StatusTypeId,
st.StatusTypeName,
COUNT(w.StatusTypeId) AS StatusCount
FROM
Table1 w LEFT OUTER JOIN
StatusType st ON st.StatusTypeId = w.StatusTypeId
WHERE
w.ExpectedStartDate BETWEEN '1/10/2011' AND '04/14/2011'
GROUP BY
datepart(M, w.ExpectedStartDate),
datepart(yyyy, w.ExpectedStartDate),
w.StatusTypeId,
st.StatusTypeName

Resources