Access Pivot Query - sql

I want to create a crosstab query where the pivot is a field with natural numbers (delayed days of a document) but I want to group them (those documents delayed less than 1 week, then those delayed less than two weeks, and then the rest of documents) but I try and I only have those whose delayed days are just 1 week and no less and so on. This is my code:
TRANSFORM Count(BlueCielo.[Document Number]) AS [CuentaDeDocument Number1]
SELECT Documentos.[Disciplina Interna], BlueCielo.[Client Response Return Status], Count(BlueCielo.[Document Number]) AS [CuentaDeDocument Number]
FROM BlueCielo INNER JOIN Documentos ON BlueCielo.[Document Number] = Documentos.[Numero Documento Cliente]
WHERE (((Documentos.[Documento Interno])="N"))
GROUP BY Documentos.[Disciplina Interna], BlueCielo.[Client Response Return Status]
ORDER BY Documentos.[Disciplina Interna], BlueCielo.[Client Response Return Status]
PIVOT BlueCielo.[Delayed Days] in (0,7,14,21);
the part that I do not know how to implement is just the last paragraph:
PIVOT BlueCielo.[Delayed Days] in (0,7,14,21);
(BlueCielo is my table and [Delayed Days] is the field with the data).
When I try with
PIVOT BlueCielo.[Delayed Days] in (0,>7,>14,<14);
it gives me an error.
Can anyone help me? Thanks a lot!!

I have try with this and I have solve the problem!
PIVOT IIf([Delayed Days]<1,"0 dias",IIf([Delayed Days]<7,"<1 wek",IIf([Delayed Days]<14,"<2 weeks",IIf([Delayed Days]<21,"<3 weeks",">3 weeks"))));

Related

How to add 2nd price column in SQL when info is normally stored on 2 separate rows

I currently have a very simple SQL script, which provides the sell price for a special customer of ours, who gets Priceline "J". I'd like to add a column of Retail pricing as well for them to reference, which is normally Priceline "R". My query currently looks like this:
SELECT RS_PCL.SKU,
RS_PCL.SKU_DESC,
RS_PCL.PACKAGE,
RS_PCL.PRICE AS [Sell Price],
RS_PCL.STD AS [Start Date],
RS_PCL.END AS [End Date]
FROM RS_PCL
WHERE RS_PCL.PRICELINE = "J"
Would anyone be able to help me figure out how I could add the "R" price line as another column instead of separate rows?
I can add WHERE RS_PCL.PRICELINE IN ("J","R") but it would create a separate row for each Retail price, instead of in the column next to it. I've seen examples of a separate SELECT CASE WHEN, but not sure exactly how the syntax works.
The prices are always going to have the same start date, so it would just need to join where the SKU matches and the Start Date matches.
NOTE : IM sorry I accidentally edited your answer, not my question...
Revised: Running into errors with this code still, saying "Your query does not include the specified expression 'GL Type' as part of an aggregate function" or would say each field that isn't included in the group by clause
SELECT RS_PCL.[GL Type],
RS_PCL.SKU,
RS_PCL.[SKU Desc],
RS_PCL.Supplier,
RS_PCL.[Case UPC],
RS_PCL.[Pack UPC],
RS_PCL.[Unit UPC],
RS_PCL.PDCN,
RS_PCL.Package,
RS_PCL.[Price Start Date],
RS_PCL.[Price End Date],
Iif( RS_PCL.PRICELINE = "J" , RS_PCL.Price , Null) AS [Sell Price],
Iif( RS_PCL.PRICELINE = "R" , RS_PCL.Price , Null) AS [Retail Price],
RS_PCL.Cost,
RS_PCL.Tax,
RS_PCL.Freight
FROM RS_PCL
WHERE (RS_PCL.PRICELINE IN ("J","R"))
Tested the Self Join query listed below, I keep getting a "Syntax Error in FROM Clause" with this query.
SELECT J.*, R.R_PRICE FROM RS_PCL AS J
INNER JOIN SELECT (RS_PCL.SKU, RS_PCL.[Price Start Date], RS_PCL.Price AS R_PRICE FROM RS_PCL WHERE RS_PCL.PRICELINE = "R") AS R
ON J.SKU = R.SKU AND J.[Price Start Date] = R.[Price Start Date]
WHERE RS_PCL.Priceline = "J"
SELECT CASE does not work in Access query. Use IIf() or Switch() or Choose().
Perhaps a CROSSTAB query or emulate CROSSTAB with expressions to create fields. Presuming, as indicated in question title, there is one "J" and one "R" record for each data combination:
SELECT SKU, SKU_DESC, PACKAGE, STD, END,
Max(IIf(PRICELINE = "J", PRICE, Null)) AS J,
Max(IIf(PRICELINE = "R", PRICE, Null)) AS R
FROM RS_PCL
GROUP BY SKU, SKU_DESC, PACKAGE, STD, END
Or a self-join, assuming only fields needed as unique identifier are SKU and STD:
SELECT J.*, R.R_PRICE FROM RS_PCL AS J
INNER JOIN (SELECT SKU, STD, PRICE AS R_PRICE FROM RS_PCL WHERE PRICELINE = "R") AS R
ON J.SKU = R.SKU AND J.STD = R.STD
WHERE PRICELINE = "J";
This would be useful on a report but useless for a data entry form.
Yet another approach would use DLookup() domain aggregate function. Domain aggregate function can cause slow performance in query or form but the dataset would be editable.

Getting the wrong Count result in ms access

I have written an SQL query to try and get some information on a group of trees by forest type. However, when I run this query, the Count(T_Plots.ID_plot) AS [Plots/Forest Type], returns the same numbers as the Count(T_Trees.ID_Tree) AS [Trees/Forest Type]. These numbers are way too high, since the entire T_Plots table only has 175 records, while in the results table it returns outcomes as high as 4290.
What did I overlook that is causing these wrong numbers, and how do I get the correct number of plots per forest type?
SELECT
T_Plots.Forest_type,
Count(T_Plots.ID_plot) AS [Plots/Forest Type],
Count(T_Trees.ID_Tree) AS [Trees/Forest Type],
[Trees/Forest Type]/[Plots/Forest Type]*10 AS [Trees/Ha],
Avg([T_Trees.DBH (cm)])/100*Avg([T_Trees.Height (m)])*0.7*[Trees/Ha] AS [Volume (m3)/Ha],
3.142*(((Avg([T_Trees.DBH (cm)])/2)^2)/100)*[Trees/Ha] AS [BA (m2)/Ha]
FROM T_Plots INNER JOIN T_Trees
ON T_Plots.ID_plot = T_Trees.ID_plot
GROUP BY T_Plots.Forest_type
Images:T_Plots T_Trees Results
I think a DISTINCT might solve your problem. Try:
SELECT
T_Plots.Forest_type,
Count(Distinct T_Plots.ID_plot) AS [Plots/Forest Type],
Count(Distinct T_Trees.ID_Tree) AS [Trees/Forest Type],
[Trees/Forest Type]/[Plots/Forest Type]*10 AS [Trees/Ha],
Avg([T_Trees.DBH (cm)])/100*Avg([T_Trees.Height (m)])*0.7*[Trees/Ha] AS [Volume (m3)/Ha],
3.142*(((Avg([T_Trees.DBH (cm)])/2)^2)/100)*[Trees/Ha] AS [BA (m2)/Ha]
FROM T_Plots INNER JOIN T_Trees
ON T_Plots.ID_plot = T_Trees.ID_plot
GROUP BY T_Plots.Forest_type

Multiple joins to create a cross tab

I have two queries I want to join so I can get the percentages from each department of completed work orders but not sure how to go about it. I know I want a join and a crosstab query so I can display the results in a report.
The first query calculates the numerator,
SELECT
Count(MaximoReport.WorkOrder) AS CountOfWorkOrder,
MaximoReport.[Assigned Owner Group]
FROM MaximoReport
WHERE (
((MaximoReport.WorkType) In ("PMINS","PMOR","PMPDM","PMREG","PMRT"))
AND ((MaximoReport.Status) Like "*COMP")
AND ((MaximoReport.[Target Start])>=DateAdd("h",-1,[Enter the start date])
AND (MaximoReport.[Target Start])<DateAdd("h",23,[Enter the end date]))
AND ((MaximoReport.ActualLaborHours)<>"00:00")
AND ((MaximoReport.ActualStartDate)>=DateAdd("h",-11.8,[Enter the start date])
AND (MaximoReport.ActualStartDate)<DateAdd("h",23,[Enter the end date]))
)
GROUP BY MaximoReport.[Assigned Owner Group];
While the second query calculates the denominator:
SELECT
Count(MaximoReport.WorkOrder) AS CountOfWorkOrder,
MaximoReport.[Assigned Owner Group]
FROM MaximoReport
WHERE (
((MaximoReport.WorkType) In ("PMINS","PMOR","PMPDM","PMREG","PMRT"))
AND ((MaximoReport.Status)<>"CAN")
AND ((MaximoReport.[Target Start])>=DateAdd("h",-11.8,[Enter the start date])
AND (MaximoReport.[Target Start])<DateAdd("h",23,[Enter the end date])))
GROUP BY MaximoReport.[Assigned Owner Group];
Please advise how I can join the two queries to get the percentages of the departments and then do a crosstab query.
If there is a better way of doing this please also let me know.

Need MS Access Form Field to automatically Calculate and Allocate Costs based on given Parameters

Below is my mock database that I am using. I have four different tables: Tbl_MainDatabase, Tbl_InsuranceCoverage, Tbl_MatterDetail, and Tbl_PaymentProcessing.
What I want -
I want my form to determine the remaining Retention Limit (i.e., Retention Limit for the applicable policy - sum of invoices for the same Claim Number )
According to the mock database, the required answer should be [ $2500 - (300+700+355)] as highlighted for your convenience
What I tried
I used the help of Graphical representation through the following query:
SELECT [Claim Number], Sum([Net Invoice Amount])
FROM [PaymentProcessing]
GROUP BY [Claim Number]
This method works to show me how much I spent per claim number so far in the form of a graph. However I want to display the remaining amount.
Any Help is appreciated :)
I am one month old at using Access. But I am trying my best to learn
Thank you in advance!
SELECT
IC.[Retention Limit]-SUM([Net Invoice Amt]) AS Remaining, MD.[Claim Number], IC.[Retention Limit], IC.InsuranceID
FROM tbl_InsuranceCoverage IC
INNER JOIN tbl_MatterDetail MD ON ic.InsuranceID = MD.Policy
INNER JOIN tbl_PaymentProcessing PP ON MD.MatterDetailID=pp.MatterDetailID AND MD.[Claim Number]=pp.[Claim Number]
GROUP BY MD.[Claim Number], IC.[Retention Limit], IC.InsuranceID
See if this works. Havent tested it but seems simple. You can remove the extra columns, but this will hlep you understand joins a bit
For All the New users The above code by #Doug Coats works perfectly.
Make Sure All the Foreign Key and Primary Keys is linked in the Relationship Property. ( One of the way To do this in the Query is - Right click on the Query and select Design View --> Right click again on the grey space and Select Show all Tables Now Drag your Primary Key of the table and drop at the foreign Key on the other table --> This will create a relationship between both for the Query Purpose.
This will also Prevent Data from Duplication in the query then use a similar code as described by Doug Coats in the above comment in the SQL View
SELECT [Insurance Coverage].[Retention Unit]-Sum([Net Invoice Amount]) AS Remaining, [Matter Detail].[Claim Number], [Insurance Coverage].[Retention Unit], [Matter Detail].Policy
FROM (([Main Database] INNER JOIN [Matter Detail] ON [Main Database].[Database ID] = [Matter Detail].[Short Name]) INNER JOIN [Payment Processing] ON ([Matter Detail].[Matter Detail ID] = [Payment Processing].[Matter Detail ID]) AND ([Main Database].[Database ID] = [Payment Processing].[Short Name])) INNER JOIN [Insurance Coverage] ON [Matter Detail].Policy = [Insurance Coverage].[Insurance ID]
GROUP BY [Matter Detail].[Claim Number], [Insurance Coverage].[Retention Unit], [Matter Detail].Policy;
You can then display this query in the form - I am still evaluating best way to display this query probably in a Combo Box (Not sure if any other controls has a row source)
Thank you

T-SQL Query will not return 0 value for a Sum

I have a query where I'm calculating Days of Therapy for medications. I want to have 0 values to show for months that have no data. Currently the query returns no record if the Sum is 0. Can't seem to figure this out. See the Query Below:
If I were to comment out identifiers related to the DOT_ALL table along with the Where Clause I get 60 rows, 1 for each month for the past 5 years. However, otherwise i get only 57 for the drug in the Where Clause since there are not DOTs for Aug 2016, April 2016 and Jan 2015.
Thanks in advance.
----------------------------------------------------------------------------
SELECT
AMS.[Medication Name]
, SUM(AMS.DOT) AS DOT
, PD.[Patient Days]
, PD.[Month_Name]
, PD.[Fiscal_Month]
, PD.[Accounting_Year]
, PD.[Year]
FROM
DW_PROD.dbo.Patient_Days_By_Month PD
Left JOIN [DW_PROD].[dbo].[DOTS_All] AMS ON (PD.Month_Name = AMS.Month AND PD.Year = AMS.Year)
WHERE
[Medication Name] = 'CEFUROXIME'
GROUP BY
AMS.[Medication Name]
, PD.[Patient Days]
, PD.[Month_Name]
, PD.[Fiscal_Month]
, PD.[Accounting_Year]
, PD.[Year]
ORDER BY
ACCOUNTING_YEAR
,FISCAL_MONTH
This may be the cheapest solution, under the assumption that Patient_Days_By_Month is already some kind of calendar.
SELECT
'CEFUROXIME' AS [Medication Name],
SUM(AMS.DOT) AS DOT,
PD.[Patient Days],
PD.[Month_Name],
PD.[Fiscal_Month],
PD.[Accounting_Year],
PD.[Year]
FROM DW_PROD.dbo.Patient_Days_By_Month PD
LEFT JOIN [DW_PROD].[dbo].[DOTS_All] AMS
ON PD.Month_Name = AMS.Month
AND PD.Year = AMS.Year
AND [Medication Name] = 'CEFUROXIME'
GROUP BY
PD.[Patient Days],
PD.[Month_Name],
PD.[Fiscal_Month],
PD.[Accounting_Year],
PD.[Year]
ORDER BY
PD.ACCOUNTING_YEAR,
PD.FISCAL_MONTH
JOIN conditions do not need to refer to columns in other tables, they can as well contain constants.
The medication name was originally restricted in the WHERE clause - that eliminated all non-cefuroxime records from the resultset.