Creating a Month Bucket from Query Result - sql

I have the following query result:
But I want to group the results by number, and categorize the quantity by month, so the resulting output would be:
How can I create a month bucket to pick up the date and make it a column and place the values accordingly. Here is my attempt so far:
select converT(varchar,year(NewShipDate)) + 'M' + MonthBucket,
*
from(
select ItemNumber, des.[Product Family], ItemDescription, des.Country, month(RequestedShipDate) as 'Month', ItemOrderedQuantity
from FS_COLine co
join FS_Item it on co.ItemKey = it.ItemKey
left outer join FIN_PLANCAP_2..ProductDescriptions des on it.ItemNumber collate database_default = des.RICNum
where RequestedShipDate >= convert(datetime, '01/01/2016', 120) and
RequestedShipDate <= convert(datetime, '12/31/2016', 120) and
isNumeric(it.ItemNumber) = 1 and
isNumeric(des.RICNum) = 1
--and it.ItemNumber = 35191305
group by ItemNumber, des.[Product Family], ItemDescription, des.Country, month(RequestedShipDate), ItemOrderedQuantity
order by ItemNumber
)A

Related

SQL select distinct from a concatenated column

This query almost does what I want
SELECT staging.dbo.ITEM_CODES.ITEM_CODE, MAX(dbo.OC_VDAT_AUX.UDL40) AS SAMPLEDATE,
CONCAT(RTRIM(dbo.OC_VDATA.UDL1), RTRIM(dbo.OC_VDATA.UDL6)) as LinkID
FROM dbo.OC_VDATA
INNER JOIN dbo.OC_VDAT_AUX ON dbo.OC_VDATA.PARTNO = dbo.OC_VDAT_AUX.PARTNOAUX AND dbo.OC_VDATA.DATETIME = dbo.OC_VDAT_AUX.DATETIMEAUX
INNER JOIN stagingPLM.dbo.ITEM_CODES ON LEFT(dbo.OC_VDATA.PARTNO, 12) = staging.dbo.ITEM_CODES.SPEC_NO
AND LEFT(dbo.OC_VDAT_AUX.PARTNOAUX, 12) = stagingPLM.dbo.ITEM_CODES.SPEC_NO
INNER JOIN stagingPLM.dbo.PLANTS ON dbo.OC_VDATA.UDL1 = staging.dbo.PLANTS.PLANT_CODE
WHERE (CONVERT(DATETIME, dbo.OC_VDAT_AUX.UDL40) > DATEADD(day, - 30, GETDATE()))
GROUP BY CONCAT(RTRIM(dbo.OC_VDATA.UDL1), RTRIM(dbo.OC_VDATA.UDL6)),staging.dbo.ITEM_CODES.ITEM_CODE
Sample Table generated by query:
The end result that I am trying to achieve is the latest ITEM_CODE per unique LinkID Note the first and last rows in the table. The last row should not be pulled by the query.
How do I modify this query to make that happen?
I have tried various placements for DISTINCT and sub queries in the select and where statements.
I would do in your case with ROW_NUMBER window function and CTE.
Solution can be like this:
WITH FilterCTE AS
(
SELECT staging.dbo.ITEM_CODES.ITEM_CODE, MAX(dbo.OC_VDAT_AUX.UDL40) AS SAMPLEDATE,
CONCAT(RTRIM(dbo.OC_VDATA.UDL1), RTRIM(dbo.OC_VDATA.UDL6)) AS LinkID,
ROW_NUMBER() OVER (PARTITION BY CONCAT(RTRIM(dbo.OC_VDATA.UDL1), RTRIM(dbo.OC_VDATA.UDL6)) ORDER BY MAX(dbo.OC_VDAT_AUX.UDL40)) AS RowNumber
FROM dbo.OC_VDATA
INNER JOIN dbo.OC_VDAT_AUX ON dbo.OC_VDATA.PARTNO = dbo.OC_VDAT_AUX.PARTNOAUX AND dbo.OC_VDATA.DATETIME = dbo.OC_VDAT_AUX.DATETIMEAUX
INNER JOIN stagingPLM.dbo.ITEM_CODES ON LEFT(dbo.OC_VDATA.PARTNO, 12) = staging.dbo.ITEM_CODES.SPEC_NO
AND LEFT(dbo.OC_VDAT_AUX.PARTNOAUX, 12) = stagingPLM.dbo.ITEM_CODES.SPEC_NO
INNER JOIN stagingPLM.dbo.PLANTS ON dbo.OC_VDATA.UDL1 = staging.dbo.PLANTS.PLANT_CODE
WHERE (CONVERT(DATETIME, dbo.OC_VDAT_AUX.UDL40) > DATEADD(day, - 30, GETDATE()))
GROUP BY CONCAT(RTRIM(dbo.OC_VDATA.UDL1), RTRIM(dbo.OC_VDATA.UDL6)),staging.dbo.ITEM_CODES.ITEM_CODE
)
SELECT *
FROM FilterCTE
WHERE RowNumber = 1

Getting latest date in SQL query

I am running this query right now:
WITH Result AS (
select distinct
--pump.Product_PN,
--pump.product_name,
mot.Motor_pn,
Mot.Motor_name,
mas.STLAN AS Usage,
po.DATUV as change_date,
mot.[Procurement type],
mot.Plant as plant,
po.IDNRK AS Component_PN,
mak.MAKTG as component_name
FROM dbo.TBLMAST AS mas
INNER JOIN dbo.TBLSTPO AS po
ON mas.STLNR = po.STLNR
INNER JOIN dbo.TBLMAKT AS mak
ON mak.MATNR = po.IDNRK
--INNER JOIN ['Pumps to motor$'] AS pump
--ON pump.[Motor Product Number] = SUBSTRING(mas.MATNR, PATINDEX('%[^0 ]%', mas.MATNR + ' '), LEN(mas.MATNR))
INNER JOIN Grundfos_motors AS mot
ON mot.Motor_PN = SUBSTRING(mas.MATNR, PATINDEX('%[^0 ]%', mas.MATNR + ' '), LEN(mas.MATNR))
where mas.STLAN = '8' and mot.Motor_PN = '78085617' and mak.MAKTG like '%stator%'
)
select motor_pn, motor_name, plant, change_date, Component_PN, Component_name, cast(getdate() as date) as Date_of_Extraction_date
from result
order by change_date DESC;
The result of this query is this:
From this query result, I want to run another query where the change_date is set to the latest. So I only want to retrieve the data for the latest date and rest is excluded. Something like:
Can anyone help?
You should be able to do:
select motor_pn, motor_name, plant, change_date, Component_PN, Component_name,
cast(getdate() as date) as Date_of_Extraction_date
from (select r.*,
row_number() over (partition by motor_pn order by change_date desc) as seqnum
from result r
) r
where seqnum = 1;

SQL Row Order based on Columns

I am trying to implement an order column based on THREADPK1 and Date columns in my query.
Example Results (with desired column on end called date_position :
ThreadSourceKey CourseNumber Date ReadCount Date Position
1518055 0701117023LFC 2016-08-24 18 1
1522610 0701117023LFC 2016-08-24 2 1
5443433 0701117023LFC 2016-08-25 1 1
5443433 0701117023LFC 2016-08-27 1 2
5443344 0701117023LFC 2016-08-21 1 1
5443344 0701117023LFC 2016-08-20 1 2
This is my query: Interested to know how to incorporate the ordering of Date position.
SELECT DISTINCT rs.threadsourcekey,
dc.coursenumber,
CONVERT (DATE, rs.modifieddate, 103) AS 'Date',
Sum(rs.recentreadcount) AS ReadCount
FROM customfinal.rsreportingfactforumreadcounts rs
INNER JOIN #threads threads
ON rs.threadsourcekey = threads.threadsourcekey
INNER JOIN final.dimcourse dc
ON rs.coursekey = dc.coursekey
WHERE rs.coursekey = #CourseKey
AND rs.modifieddate >= Dateadd(day, -7, #DefaultDate)
AND rs.usersourcekey >- 1
AND rs.recentreadcount <> 0
GROUP BY rs.threadsourcekey,
dc.coursenumber,
CONVERT (DATE, rs.modifieddate, 103)
select
ThreadSourceKey,
CourseNumber,
[Date],
ReadCount,
Date_Position = row_number() over (partition by ThreadSourceKey order by [Date])
from
(your sql statement) a
Assuming your query works fine, adding ROW_NUMBER() should get you what you want.
Note that since your GROUP BY has CONVERT (DATE, rs.modifieddate, 103) you need to use exactly that to partition by.
SELECT DISTINCT rs.threadsourcekey,
dc.coursenumber,
CONVERT (DATE, rs.modifieddate, 103) AS 'Date',
Sum(rs.recentreadcount) AS ReadCount,
ROW_NUMBER() OVER (partition by rs.threadsourcekey order by CONVERT (DATE, rs.modifieddate, 103)) AS [DATE POSITION]
FROM customfinal.rsreportingfactforumreadcounts rs
INNER JOIN #threads threads
ON rs.threadsourcekey = threads.threadsourcekey
INNER JOIN final.dimcourse dc
ON rs.coursekey = dc.coursekey
WHERE rs.coursekey = #CourseKey
AND rs.modifieddate >= Dateadd(day, -7, #DefaultDate)
AND rs.usersourcekey >- 1
AND rs.recentreadcount <> 0
GROUP BY rs.threadsourcekey,
dc.coursenumber,
CONVERT (DATE, rs.modifieddate, 103)
Here is a snippet if you want to pick at and see how it works.
SELECT threadsourcekey,
ModDate AS 'Date',
Sum(ReadCount) AS ReadCount ,
ROW_NUMBER() OVER (partition by threadsourcekey order by ModDate) AS [DATE POSITION]
FROM
( VALUES
(1518055, '2016-08-24', 1),
(1518055, '2016-08-24', 1),
(1518055, '2016-08-24', 1),
(1522610, '2016-08-24', 1),
(1522610, '2016-08-24', 1),
(5443433, '2016-08-25', 1),
(5443433, '2016-08-27', 1),
(5443344, '2016-08-21', 1),
(5443344, '2016-08-20', 1)
) As Tbl (ThreadSourceKey, ModDate, ReadCount)
GROUP BY threadsourcekey,
ModDate

Adding a max date subquery to a group by clause

I need to add a max transactional date to this report, so I can see the most recent transaction date for a patient who does not fall under the parameters in the query. This report will be going into a crystal report and I plan to put the last date of service date in the group header for each patient. The code below is to get the max date for each patient. I need the results inserted, so it takes the patients who fall under the below report and gives their max date. Regardless of what is entered for a date. Thank you in advance. SQL Server 2005.
select
patient_id,
Max(proc_chron)
from patient_clin_tran pct
group by patient_id
The Code for the transaction
select patient_id,
(select p.case_status from patient p where p.patient_id = btb.patient_id and p.episode_id = (select max(episode_id) from patient p2 where p2.patient_id = p.patient_id)) as 'Status',
(select p.lname +', '+ p.fname from patient p where p.patient_id = btb.patient_id and p.episode_id = (select max(episode_id) from patient p2 where p2.patient_id = p.patient_id)) AS 'client',
Coverage_plan_id,
(select proc_code from billing_transaction bt where bt.clinical_transaction_no = btb.clinical_transaction_no and bt.coverage_plan_id=btb.coverage_plan_id and bt.coverage_plan_id = btb.coverage_plan_id) as 'Procedure',
proc_chron,
(select billing_amt from billing_transaction bt where bt.clinical_transaction_no = btb.clinical_transaction_no and bt.coverage_plan_id = btb.coverage_plan_id) as 'Billing Amount',
balance_amount,
(select max (accounting_date) from billing_ledger bl where bl.clinical_transaction_no = btb.clinical_transaction_no and subtype = 'pa' and bl.coverage_plan_id = 'standard') as 'Last Payment on Trans',
(select max (instrument_date) from payment p where p.patient_id = btb.patient_id and p.coverage_plan_id = 'standard') as 'Last Payment on Acct',
(select sum(balance_amount) from billing_transaction_balance btb2 where btb2.patient_id=btb.patient_id and btb2.coverage_plan_id=btb.coverage_plan_id and proc_chron <= CONVERT(CHAR(6), DATEADD(year, -1, DATEDIFF(day, 0,GETDATE())), 112) + '01' and btb2.coverage_plan_id in('standard')) AS 'Balance'
from billing_transaction_balance btb
where proc_chron <= CONVERT(CHAR(6), DATEADD(year, -1, DATEDIFF(day, 0, GETDATE())), 112) + '01' and coverage_plan_id in('standard')
group by patient_id, proc_chron, coverage_plan_id, balance_amount, clinical_transaction_no
In your transaction code, you need to add all the Select columns which are not being aggregated to the Group By. I count 8 non-aggregated columns in the Select statement, so you must have all 8 in the Group By.

I have two tables with common Quote_No and I need to sum Qty in Quote_Items with Required by Date in Table Quotes

I am trying to get the sum of "Qty" in a Table A called "Quote_Items" based on a "Required_by_Date" from Table B called Quotes. Both tables have a common "Quote_No" The required date is one month ago.
I have used the following but it produces a NULL, but I cannot see why
select sum(Qty)
from quotes.Quote_Items_Quantities
left outer join quotes.Quotes on (Quote_Required_by_Date = Qty)
WHERE (DatePart(yy, Quote_Required_by_Date) = DatePart(yy, DateAdd(m,1,getdate()))) and
datepart(m,Quote_Required_by_Date) = datepart(m,dateadd(m,1,getdate()))
Any suggestions what I am doing wrong here.
Try this:
SELECT SUM(i.Qty)
FROM Quote_Items i
JOIN Quotes q on i.Quote_No = q.Quote_No
AND CONVERT(varchar, q.Required_by_Date, 112) = CONVERT(varchar, DATEADD(month, -1, getdate()), 112)
or this (equivalent without using JOIN)
SELECT SUM(i.Qty)
FROM Quote_Items i
WHERE EXISTS(SELECT 1 FROM Quotes WHERE Quote_No = i.Quote_No AND CONVERT(varchar, Required_by_Date, 112) = CONVERT(varchar, DATEADD(month, -1, getdate()), 112))
Your query is producing NULL because of the join condition. You have
on Quote_Required_by_Date = Qty
However, the date is not going to match the quantity. Instead, you need to match on the Quote_No, according to your question:
select sum(Qty)
from quotes.Quote_Items_Quantities qiq left outer join
quotes.Quotes q
on q.Quote_Required_by_Date = qiq.Qty
WHERE (DatePart(yy, Quote_Required_by_Date) = DatePart(yy, DateAdd(m,1,getdate()))) and
datepart(m,Quote_Required_by_Date) = datepart(m,dateadd(m,1,getdate()));
You can also simplify your query by using the month() and year() functions:
select sum(Qty)
from quotes.Quote_Items_Quantities qiq left outer join
quotes.Quotes q
on q.Quote_Required_by_Date = qiq.Qty
WHERE year(Quote_Required_by_Date) = year(DateAdd(m, 1, getdate()) and
month(Quote_Required_by_Date) = month(dateadd(m,1,getdate());
Finally, you mind find it useful to use group by and get the results for many months:
select year(Quote_Required_by_Date), month(Quote_Required_by_Date), sum(Qty)
from quotes.Quote_Items_Quantities qiq left outer join
quotes.Quotes q
on q.Quote_Required_by_Date = qiq.Qty
group by year(Quote_Required_by_Date), month(Quote_Required_by_Date)
order by 1 desc, 2 desc;