Adding a date range to existing query - date-range

I have just started a new job and am working with existing queries. As I am no expert on SQL I'm wondering if a date range such as 2015-8-1 through 2015-8-31 can be inserted into the query below. Any help offered is greatly appreciated.
SELECT
RANK() OVER (PARTITION BY DoctorFacility.ListName ORDER BY ApptSlot.Start)
as SlotNumber
, DoctorFacility.ListName as ProviderName
, ApptSlot.Start as ApptStartTime
, AppointmentsAlloc.Type as ApptType
INTO #TEMP
FROM CentricityPS.dbo.ApptSlot ApptSlot
INNER JOIN CentricityPS.dbo.AppointmentsAlloc AppointmentsAlloc
ON ApptSlot.ApptSlotId=AppointmentsAlloc.ApptSlotId
INNER JOIN CentricityPS.dbo.Schedule Schedule
ON ApptSlot.ScheduleId=Schedule.ScheduleId
INNER JOIN CentricityPS.dbo.DoctorFacility DoctorFacility
ON Schedule.DoctorResourceId=DoctorFacility.DoctorFacilityId
WHERE AppointmentsAlloc.Type IN
(
'Behavioral Health - 30'
,'Behavioral Health 45'
,'Established Patient - 15'
,'Established Patient - 20'
,'Fin Counsel - 30'
,'Gyn Visit - 15'
,'Pediatric Visit - 15'
)
AND ApptSlot.ListOrder=1
AND ApptSlot.Status IS NULL
AND ApptSlot.Start>= GETDATE()
ORDER BY DoctorFacility.ListName
SELECT
ProviderName
, ApptStartTime
, ApptType
FROM #TEMP
WHERE SlotNumber = 3
ORDER BY ProviderName
DROP TABLE #TEMP

There are two separate select queries here. It would be done the same way for either part of the query regardless. Just add it to your WHERE statement
AND ApptSlot.Start>= 2015-8-1
AND ApptSlot.Start<= 2015-8-31
Another syntax would be
AND ApptSlot.Start between 2015-8-1 and 2015-8-31
Ideally you want to pass those begin and start dates as variables so values would not be hard coded. It might look more like this.
AND ApptSlot.Start between #StartDate and #EndDate

Related

RedShift Correlated Sub-query

Need your help. I am trying to convert below SQL query into RedShift, but getting error message "Invalid operation: This type of correlated subquery pattern is not supported yet"
SELECT
Comp_Key,
Comp_Reading_Key,
Row_Num,
Prev_Reading_Date,
( SELECT MAX(X) FROM (
SELECT CAST(dateadd(day, 1, Prev_Reading_Date) AS DATE) AS X
UNION ALL
SELECT dim_date.calendar_date
) a
) as start_dt
FROM stage5
JOIN dim_date ON calendar_date BETWEEN '2020-04-01' and '2020-04-15'
WHERE Comp_Key =50906055
The same query works fine in SQL Server. Could you please help me to run it in RedShift?
Regards,
Kiru
Kiru - you need to convert the correlated query into a join structure. Not knowing the data content of your tables and the exact expected out put I'm just guessing but here's a swag:
SELECT
Comp_Key,
Comp_Reading_Key,
Row_Num,
Prev_Reading_Date,
Max_X
FROM stage5
JOIN dim_date ON calendar_date BETWEEN '2020-04-01' and '2020-04-15'
JOIN ( SELECT MAX(X) as Max_X, MAX(calendar_date) as date FROM (
SELECT CAST(dateadd(day, 1, Prev_Reading_Date) AS DATE) AS X FROM stage5
cross join
SELECT dim_date.calendar_date from dim_date
) a
) as start_dt ON a.date = dim_date.calendar_date
WHERE Comp_Key =50906055
This is just a starting guess but might get you started.
However, you are likely better off rewriting this query to use window functions as they are the fastest way to perform these types of looping queries in Redshift.
Thanks Bill. It won't work in RedShift as it still has correalted sub-query.
However I have modified query in another method and it works fine.
I am closing ticket.

How can I store the value of a subquery into a variable in Hana Studio?

I would like to know how can I store the value of subquery to use it in an operation after it recieve the value. For example:
Select IDTruck
, TruckPrice = (select "TruckPrice" from "Table1" where ("TruckID" = '123'))
, TruckUnit = (select "TruckUnit" from "Table2" )
, TruckPrice * TruckUnit as "PriceTotal"
from Table3
I just want to store the value and then use it in the operation so I don't have to do the select again.
I'm not sure why it should be necessary to store the values in variables for usage in your case. I think the calculation can be done also by joining just the data (assuming that table3 contains a reference to table1 and table2).
Your example above would also not work, because TruckPrice and TruckUnits are no atomar results.
So please try to refactor your statement to use joins.

Getting error while running an sql script in ADW

Am getting an error that goes like this:
Insert values statement can contain only constant literal values or variable references.
these are the statements in which I am getting the errors:
INSERT INTO val.summary_numbers (metric_name, metric_val, dt_create) VALUES ('Total IP Enconters',
(SELECT
count(DISTINCT encounter_id)
FROM prod.encounter
WHERE encounter_type = 'Inpatient')
,
(SELECT min(mod_loadidentifier)
FROM ccsm.stg_demographics_baseline)
);
INSERT INTO val.summary_numbers (metric_name, metric_val, dt_create) VALUES ('Total 30d Readmits',
(SELECT
count(DISTINCT encounter_id)
FROM prod.encounter_attr
WHERE
attr_name = 'day_30_readmit' AND attr_value = 1)
,
(SELECT min(mod_loadidentifier)
FROM ccsm.stg_demographics_baseline));
Change your query like this:
insert into val.summary_numbers
select
'Total IP Enconters',
(select count(distinct encounter_id)
from prod.encounter
where encounter_type = 'Inpatient'),
(select min(mod_loadidentifier)
from ccsm.stg_demographics_baseline)
When using the ADW service, I would recommend that you consider using the CTAS operation possibly combined with a RENAME. The RENAME is a metadata operation so it is fast and the CTAS is parallel where the INSERT INTO will be row by row.
You may still have a data related issue that can be hard to determine with out the create table statement.
Thanks

Maximo Conditional expression manager/Sql Query Builder

Can somebody help me in converting below mentioned query in to Maximo's where clause:
select distinct workorder.wonum from workorder inner join [assignment]
On workorder.wonum=[assignment].wonum
inner join amcrew
On amcrew.amcrew=[assignment].amcrew
inner join amcrewlabor
On amcrewlabor.amcrew=amcrew.amcrew
inner join labor
On amcrewlabor.laborcode=labor.laborcode
inner join person
on labor.laborcode=person.personid where amcrewlabor.laborcode='KELLYB'
KELLYB is PERSONID used here for just reference.
If you are using a custom search query in Maximo, you can try prepending your with in (your query)
For example, if you're in Maximo's work order tracking module, the application uses select * from workorder by default. Any time you add a search filter such as work order number (wonum), then the query appends to run a query as select * from workorder where wonum = '123' if 123 is the work order number you entered.
Your where clause might look something like this:
wonum in (
select distinct workorder.wonum
from workorder
join assignment on workorder.wonum=assignment.wonum
join amcrew on amcrew.amcrew=assignment.amcrew
join amcrewlabor on amcrewlabor.amcrew=amcrew.amcrew
join labor on amcrewlabor.laborcode=labor.laborcode
join person on labor.laborcode=person.personid
where amcrewlabor.laborcode='KELLYB'
)
The SQL that is generated in Microsoft Access will not necessarily work in Maximo without some modification.

Cannot link MS Access query with subquery

I have created a query with a subquery in Access, and cannot link it in Excel 2003: when I use the menu Data -> Import External Data -> Import Data... and select the mdb file, the query is not present in the list. If I use the menu Data -> Import External Data -> New Database Query..., I can see my query in the list, but at the end of the import wizard I get this error:
Too few parameters. Expected 2.
My guess is that the query syntax is causing the problem, in fact the query contains a subquery. So, I'll try to describe the query goal and the resulting syntax.
Table Positions
ID (Autonumber, Primary Key)
position (double)
currency_id (long) (references Currency.ID)
portfolio (long)
Table Currency
ID (Autonumber, Primary Key)
code (text)
Query Goal
Join the 2 tables
Filter by portfolio = 1
Filter by currency.code in ("A", "B")
Group by currency and calculate the sum of the positions for each currency group an call the result: sumOfPositions
Calculate abs(sumOfPositions) on each currency group
Calculate the sum of the previous results as a single result
Query
The query without the final sum can be created using the Design View. The resulting SQL is:
SELECT Currency.code, Sum(Positions.position) AS SumOfposition
FROM [Currency] INNER JOIN Positions ON Currency.ID = Positions.currency_id
WHERE (((Positions.portfolio)=1))
GROUP BY Currency.code
HAVING (((Currency.code) In ("A","B")));
in order to calculate the final SUM I did the following (in the SQL View):
SELECT Sum(Abs([temp].[SumOfposition])) AS sumAbs
FROM [SELECT Currency.code, Sum(Positions.position) AS SumOfposition
FROM [Currency] INNER JOIN Positions ON Currency.ID = Positions.currency_id
WHERE (((Positions.portfolio)=1))
GROUP BY Currency.code
HAVING (((Currency.code) In ("A","B")))]. AS temp;
So, the question is: is there a better way for structuring the query in order to make the export work?
I can't see too much wrong with it, but I would take out some of the junk Access puts in and scale down the query to this, hopefully this should run ok:
SELECT Sum(Abs(A.SumOfPosition)) As SumAbs
FROM (SELECT C.code, Sum(P.position) AS SumOfposition
FROM Currency As C INNER JOIN Positions As P ON C.ID = P.currency_id
WHERE P.portfolio=1
GROUP BY C.code
HAVING C.code In ("A","B")) As A
It might be worth trying to declare your parameters in the MS Access query definition and define their datatypes. This is especially important when you are trying to use the query outside of MS Access itself, since it can't auto-detect the parameter types. This approach is sometimes hit or miss, but worth a shot.
PARAMETERS [[Positions].[portfolio]] Long, [[Currency].[code]] Text ( 255 );
SELECT Sum(Abs([temp].[SumOfposition])) AS sumAbs
FROM [SELECT Currency.code, Sum(Positions.position) AS SumOfposition
FROM [Currency] INNER JOIN Positions ON Currency.ID = Positions.currency_id
WHERE (((Positions.portfolio)=1))
GROUP BY Currency.code
HAVING (((Currency.code) In ("A","B")))]. AS temp;
I have solved my problems thanks to the fact that the outer query is doing a trivial sum. When choosing New Database Query... in Excel, at the end of the process, after pressing Finish, an Import Data form pops up, asking
Where do you want to put the data?
you can click on Create a PivotTable report... . If you define the PivotTable properly, Excel will display only the outer sum.

Resources