In this condition users can visit in a schedule.
How me to create a function in oracle database that have logic are:
one month once visit (f1)
two month once visit (f2)
one week once visit (f4)
one week twice visit(f8).
So we can view data in current date fit with that condition.
Example in database with table name is mst_callplan:
cust_no : 201, sales_no:001, frequent: f1, day: monday
cust_no : 202, sales_no:001, frequent: f8, day: friday
cust_no : 203, sales_no:001, frequent: f2, day: wednesday
cust_no : 204, sales_no:001, frequent: f1, day: monday
cust_no,sales_no,frequent,and day is name of column.
From database will view row of table fit with that condition in current date. The data shown automatic when current date is change.
For the example result is: null (for this current date : 25/04/2017)
Help me for the function in database. how to create the function fit that condition.
function in that case is:
FUNCTION get_data_sales(pi_trxn_dt IN DATE)
RETURN slm_type_mst_callplan_tab IS
l_slm_type_mst_callplan_rec slm_type_mst_callplan_rec;
l_slm_type_mst_callplan_tab slm_type_mst_callplan_tab := slm_type_mst_callplan_tab();
l_return PLS_INTEGER;
ex_set_date_lang EXCEPTION;
CURSOR cur_data IS
SELECT cust_id
,sales_id
,mst_freq
,mst_day
,start_date
,end_date
,week_no
FROM mst_callplan
WHERE (upper(mst_freq) = 'F1' and week_no=4 AND
MOD(slm_pkg_utl.cnt_week(pi_start_dt => g_start_dt
,pi_end_dt => pi_trxn_dt)
,4) = 0 AND upper(TRIM(mst_day)) =
upper(TRIM(to_char(pi_trxn_dt,'Day'))))
OR
(upper(mst_freq) = 'F1'and week_no=3 AND
MOD(slm_pkg_utl.cnt_week(pi_start_dt => g_start_dt
,pi_end_dt => pi_trxn_dt)
,4) = 3 AND upper(TRIM(mst_day)) =
upper(TRIM(to_char(pi_trxn_dt,'Day'))))
OR
(upper(mst_freq) = 'F1'and week_no=2 AND
MOD(slm_pkg_utl.cnt_week(pi_start_dt => g_start_dt
,pi_end_dt => pi_trxn_dt)
,4) = 2 AND upper(TRIM(mst_day)) =
upper(TRIM(to_char(pi_trxn_dt,'Day'))))
OR
(upper(mst_freq) = 'F1'and week_no=1 AND
MOD(slm_pkg_utl.cnt_week(pi_start_dt => g_start_dt
,pi_end_dt => pi_trxn_dt)
,4) = 1 AND upper(TRIM(mst_day)) =
upper(TRIM(to_char(pi_trxn_dt,'Day'))))
OR
(upper(mst_freq) = 'F2' and week_no=2 AND
MOD(slm_pkg_utl.cnt_week(pi_start_dt => g_start_dt
,pi_end_dt => pi_trxn_dt)
,2) = 0 AND upper(TRIM(mst_day)) =
upper(TRIM(to_char(pi_trxn_dt
,'Day'))))
OR
(upper(mst_freq) = 'F2' and week_no=1 AND
MOD(slm_pkg_utl.cnt_week(pi_start_dt => g_start_dt
,pi_end_dt => pi_trxn_dt)
,2) = 1 AND upper(TRIM(mst_day)) =
upper(TRIM(to_char(pi_trxn_dt,'Day'))))
OR (upper(mst_freq) = 'F4' AND
upper(TRIM(mst_day)) =
upper(TRIM(to_char(pi_trxn_dt
,'Day'))))
OR (upper(mst_freq) = 'F8' AND
upper(TRIM(mst_day)) =
upper(TRIM(to_char(pi_trxn_dt
,'Day'))));
BEGIN
set_date_language(po_return => l_return);
IF l_return <> 0 THEN
RAISE ex_set_date_lang;
END IF;
FOR rec_dt IN cur_data
LOOP
l_slm_type_mst_callplan_tab.extend;
l_slm_type_mst_callplan_tab(l_slm_type_mst_callplan_tab.last) := slm_type_mst_callplan_rec(rec_dt.cust_id
,rec_dt.sales_id
,rec_dt.mst_freq
,rec_dt.mst_day
,rec_dt.start_date
,rec_dt.end_date
,rec_dt.week_no);
END LOOP;
RETURN l_slm_type_mst_callplan_tab;
EXCEPTION
WHEN ex_set_date_lang THEN
dbms_output.put_line('Error set date languange');
WHEN OTHERS THEN
l_slm_type_mst_callplan_tab.delete;
END get_data_sales;
Related
Given data as such:
Month ValueA
1 T
2 T
3 T
4 F
Is there a way to make a measure that would find if for each month, last three Values were True?
So the output would be (F,F,T,F)?
That would propably mean that my actual problem is solvable, which is finding from:
Month ValueA ValueB ValueC
1 T F T
2 T T T
3 T T T
4 F T F
the count of those booleans for each row, so the output would be (0,0,2[A and C],1[B])
EDIT:
Okay, I managed to solve the first part with this:
Previous =
VAR PreviousDate =
MAXX(
FILTER(
ALL( 'Table' ),
EARLIER( 'Table'[Month] ) > 'Table'[Month]
),
'Table'[Month]
)
VAR PreviousDate2 =
MAXX(
FILTER(
ALL( 'Table' ),
EARLIER( 'Table'[Month] ) - 1 > 'Table'[Month]
),
'Table'[Month]
)
RETURN
IF(
CALCULATE(
MAX( 'Table'[Value] ),
FILTER(
'Table',
'Table'[Month] = PreviousDate
)
) = "T"
&& CALCULATE(
MAX( 'Table'[Value] ),
FILTER(
'Table',
'Table'[Month] = PreviousDate2
)
) = "T"
&& 'Table'[Value] = "T",
TRUE,
FALSE
)
But is there a way to use it with unknown number of columns?
Without hard - coding every column name? Like a loop or something.
I would redo the data table in power query (upivoting the ValueX-columns) and changing T/F to 1/0. Then have a dim table with a relationship to Month, like this:
Then add a measure like this:
Three Consec T =
var maxMonth = MAX('Data'[Month])
var tempTab =
FILTER(
dimMonth;
'dimMonth'[MonthNumber] <= maxMonth && 'dimMonth'[MonthNumber] > maxMonth -3
)
var sumMonth =
MAXX(
'dimMonth';
CALCULATE(
SUM('Data'[OneOrZero]);
tempTab
)
)
return
IF(
sumMonth >= 3;
"3 months in a row";
"No"
)
Then I can have a visual like this when the slicer indicates which time window I'm looking at and the table shows if there has been 3 consecutive Ts or not.
I have this list in one column CHAR/STRING in DB:
['2020-09-05 10:15:00', '2020-09-05 10:30:00', '2020-09-05 10:45:00', '2020-09-05 11:00:00', '2020-09-05 11:15:00']
I get them to python3:
employee_id = request.args.get('id')
employee = Employee.query.filter_by(id = employee_id).first()
list_time_em = employee.free_time
print(list_time_em)
for x in list_time_em:
print(x). #try to print time in list from DB
Result
['2020-09-05 10:15:00', '2020-09-05 10:30:00', '2020-09-05 10:45:00', '2020-09-05 11:00:00', '2020-09-05 11:15:00']
['2020-09-0510#...etc
[
'
2
0
2
0
-
0
9
-
0
5
1
0
:
1
5
I try many ways to get element in LIST like below:
2020-09-05 10:15:00
2020-09-05 10:30:00
... etc
but i can't
Anyone help me please!
--------SOLUTION-------
Thanks for #Eddy
if request.args.get('do')=='add_job':
employee_id = request.args.get('id')
employee = Employee.query.filter_by(id = employee_id).first()
list_time_em = employee.free_time
datesStr = list_time_em
def getDates(datesStr):
dates = json.loads(datesStr.replace('\'', '"')) # make sure we dont break when parsing
return dates
dates = getDates(datesStr)
return render_template('add_job.html',list_time_em=dates)
i found another way:
if request.args.get('do')=='add_job':
employee_id = request.args.get('id')
employee = Employee.query.filter_by(id = employee_id).first()
list_time_em = employee.free_time
x = list_time_em
ls = x.strip('[]').replace('"','').split(',')
print(ls)
return render_template('add_job.html',list_time_em=ls)
You can use json library to accomplish this
import json
datesStr = "['2020-09-05 10:15:00', '2020-09-05 10:30:00', '2020-09-05 10:45:00', '2020-09-05 11:00:00', '2020-09-05 11:15:00']"
def getDates(datesStr):
dates = json.loads(datesStr.replace('\'', '"')) # make sure we dont break when parsing
return dates
dates = getDates(datesStr)
for date in dates:
print(date)
in your specific example:
import json
def getDates(datesStr):
dates = json.loads(datesStr.replace('\'', '"')) # make sure we dont break when parsing
return dates
employee_id = request.args.get('id')
employee = Employee.query.filter_by(id = employee_id).first()
list_time_em = employee.free_time
dates = getDates(list_time_em)
for date in dates:
print(date). #try to print time in list from DB
This is using mysql library
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="closer"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT message FROM message")
myresult = mycursor.fetchall()
li=list()
for x in myresult:
li.append(x)
print(li)
Thanks for #Eddy
if request.args.get('do')=='add_job':
employee_id = request.args.get('id')
employee = Employee.query.filter_by(id = employee_id).first()
list_time_em = employee.free_time
datesStr = list_time_em
def getDates(datesStr):
dates = json.loads(datesStr.replace('\'', '"')) # make sure we dont break when parsing
return dates
dates = getDates(datesStr)
return render_template('add_job.html',list_time_em=dates)
i found another way:
if request.args.get('do')=='add_job':
employee_id = request.args.get('id')
employee = Employee.query.filter_by(id = employee_id).first()
list_time_em = employee.free_time
x = list_time_em
ls = x.strip('[]').replace('"','').split(',')
print(ls)
return render_template('add_job.html',list_time_em=ls)
I'm trying to write an IF statement in my stored procedure, but I have no idea how.
TIPO_DOCUMENTO can be 'FAC' or 'DEV', if TIPO_DOCUMENTO is 'FAC', I will use the total_neto, total_impuesto, total, costo and precio as is. But if I have 'DEV', I will need the negative values of those fields.
begin
/*FILTRO RANGO DE FECHA*/
IF (P_FECHA_DESDE='0' OR (P_FECHA_DESDE IS NULL) OR (P_FECHA_DESDE='')) THEN
V_FECHA_DESDE = CAST('01/01/1900' AS DATE);
ELSE
V_FECHA_DESDE = CAST(:P_FECHA_DESDE AS DATE);
IF (P_FECHA_HASTA='0' OR (P_FECHA_HASTA IS NULL)OR (P_FECHA_HASTA='')) THEN
V_FECHA_HASTA = CAST('12/31/3999' AS DATE);
ELSE
V_FECHA_HASTA = CAST(:P_FECHA_HASTA AS DATE);
/*FILTRO RANGO DE VENDEDORES*/
IF (P_VENDEDOR_DESDE IS NULL) THEN P_VENDEDOR_DESDE = '';
IF (P_VENDEDOR_HASTA IS NULL) THEN P_VENDEDOR_HASTA = LOWER('ZZZZZZZZZZZZZZZ');
IF (P_VENDEDOR_HASTA = '') THEN P_VENDEDOR_HASTA = LOWER('ZZZZZZZZZZZZZZZ');
IF (NOT ((P_VENDEDOR_DESDE = '') AND (P_VENDEDOR_HASTA = LOWER('ZZZZZZZZZZZZZZZ')))) THEN
IF (P_VENDEDOR_DESDE = P_VENDEDOR_HASTA) THEN
V_WHERE = V_WHERE || ' AND (VEN.VENDEDOR_CODIGO = '''||P_VENDEDOR_DESDE||''')';
ELSE
V_WHERE = V_WHERE || ' AND (VEN.VENDEDOR_CODIGO BETWEEN '''||P_VENDEDOR_DESDE||''' AND '''||P_VENDEDOR_HASTA||''')';
/*CICLO DE LA CONSULTA SQL*/
FOR SELECT
a.tipo_documento,
a.documento,
b.nombre as vendedor,
c.producto_codigo,
c.producto_nombre as descripcion,
c.cantidad,
d.departamento_codigo,
c.deposito_codigo,
(c.descuento_unitario * c.cantidad) + (c.descuento_unitario_2 * c.cantidad) + (c.descuento_unitario_3 * c.cantidad) +(c.descuento_unitario_4 * c.cantidad) as total_descuento,
c.total_neto,
c.total_impuesto,
c.total,
a.cliente_codigo,
a.cliente_nombre,
e.direccion,
estado.nombre,
ciudad.nombre,
c.costo_unitario * c.cantidad as costo,
c.precio_unitario * c.cantidad as precio
from ventas a
join vendedores b
on a.vendedor_codigo = b.codigo
join ventas_detalles c
on a.correlativo = c.correlativo_principal
join productos_terminados d
on d.codigo_producto = c.producto_codigo
join clientes e
on a.cliente_codigo = e.codigo
join ubicacion_geografica estado
on estado.codigo = e.estado
and estado.tipo = 'E'
join ubicacion_geografica ciudad
on ciudad.codigo = e.ciudad
and ciudad.tipo = 'C'
where a.fecha_emision between :V_FECHA_DESDE and :V_FECHA_HASTA
INTO
:TIPO_DOC,
:NUM_DOC,
:VENDEDOR_NOMBRE,
:PRODUCTO_CODIGO,
:PRODUCTO_NOMBRE,
:CANTIDAD,
:DEPARTAMENTO,
:DEPOSITO,
:DESCUENTO,
:TOTAL_NETO,
:TOTAL_IMPUESTO,
:TOTAL,
:CLIENTE_CODIGO,
:CLIENTE_NOMBRE,
:CLIENTE_DIRECCION,
:ESTADO,
:CIUDAD,
:COSTO,
:PRECIO
do
begin
if (TIPO_DOC = 'DEV') then
total_neto = -total_neto ;
total_impuesto = -total_impuesto ;
total = -total ;
costo = -costo ;
precio = -precio;
suspend;
end
end
Now I can only get the negative values, regardless of whether I have FAC or DEV.
Your if is syntactically wrong for what I think you want to do. The indentation of the following suggests that all those statements should depend on the if condition:
if (TIPO_DOC = 'DEV') then
total_neto = -total_neto ;
total_impuesto = -total_impuesto ;
total = -total ;
costo = -costo ;
precio = -precio;
In reality only the first statement after the if belongs to the if condition. In other words, it is actually
if (TIPO_DOC = 'DEV') then
total_neto = -total_neto ;
total_impuesto = -total_impuesto ;
total = -total ;
costo = -costo ;
precio = -precio;
If you want all those statements to depend on the if, you need to define a block using begin and end:
if (TIPO_DOC = 'DEV') then
begin
total_neto = -total_neto ;
total_impuesto = -total_impuesto ;
total = -total ;
costo = -costo ;
precio = -precio;
end
See also IF ... THEN ... ELSE in the Firebird 2.5 Language Reference.
Not an answer, just an advice, using syntactic highlighting.
FOR SELECT
....
do
if (TIPO_DOC = 'DEV') then
total_neto = -total_neto ;
total_impuesto = -total_impuesto ;
total = -total ;
costo = -costo ;
precio = -precio;
This code has few problems with me.
If within loop - often it may slow down execution. So if IF condition is not dependent upon loop data - if it is invariant - it might make sense to move If outside of loop.
Future compatibility - what would you procedure do if for example TIPO_DOCUMENTO = 'BE-BE-BE'? Should not happen today? But it can happen tomorrow as new functions would be added to the program. It even can happen today because of some bug.
Personally i would do it different way:
DECLARE VARIABLE COEFF SMALLINT;
....
COEFF = CASE TIPO_DOC
WHEN 'DEV' THEN -1
WHEN 'FAC' THEN +1
ELSE :COEFF / 0 /* generate error if prohibited value */
END;
-- shorthand
-- COEFF = DECODE( TIPO_DOC, 'DEV',-1, 'FAC',+1, :COEFF / 0 );
FOR SELECT....
DO
total_neto = COEFF*total_neto ;
total_impuesto = COEFF*total_impuesto;
....
More strange things: P_VENDEDOR_DESDE = ''; - thus this variable is some text type, like VarChar or CHAR or BLOB SUB_TYPE TEXT.
Then why VEN.VENDEDOR_CODIGO BETWEEN '''||P_VENDEDOR_DESDE||''' AND '''||P_VENDEDOR_HASTA||''' ???
Why not just VEN.VENDEDOR_CODIGO BETWEEN P_VENDEDOR_DESDE AND P_VENDEDOR_HASTA ?
I have the following Oracle SQL query
select /*+ORDERED */ payr.payroll_name payroll_name,
nvl(papf.employee_number, papf.npw_number) employee_number,
nvl
(
xxpay_util.safe_to_number
(
xxpay_util_element.get_run_result
(
p_business_group_id => paaf.business_group_id, -- in number
p_payroll_id => paaf.payroll_id, -- in number
p_payroll_action_id => null, -- in number,
p_start_period => mon.real_month_start, -- in date
p_end_period => mon.real_month_end, -- in date
p_element_name_regex => '^Disability Cover ER$', -- in varchar2 '^Disability Cover ER Opt Out$'
p_input_value => 'Pay Value', -- in varchar2
p_assignment_id => paaf.assignment_id, -- in number
p_aggregation => 'sum', -- in varchar2
p_round => 2 -- in number default 2
)
),
0
) disability_benefit,
nvl
(
xxpay_util.safe_to_number
(
xxpay_util_element.get_run_result
(
p_business_group_id => paaf.business_group_id, -- in number
p_payroll_id => paaf.payroll_id, -- in number
p_payroll_action_id => null, -- in number,
p_start_period => mon.real_month_start, -- in date
p_end_period => mon.real_month_end, -- in date
p_element_name_regex => '^Death Cover ER Opt Out$', -- in varchar2
p_input_value => 'Pay Value', -- in varchar2
p_assignment_id => paaf.assignment_id, -- in number
p_aggregation => 'sum', -- in varchar2
p_round => 2 -- in number default 2
)
),
0
) death_cover,
nvl
(
xxpay_util.safe_to_number
(
xxpay_util_element.get_run_result
(
p_business_group_id => paaf.business_group_id, -- in number
p_payroll_id => paaf.payroll_id, -- in number
p_payroll_action_id => null, -- in number,
p_start_period => mon.real_month_start, -- in date
p_end_period => mon.real_month_end, -- in date
p_element_name_regex => '^Funeral Cover ER$', -- in varchar2 '^Funeral Cover ER Opt Out$'
p_input_value => 'Pay Value', -- in varchar2
p_assignment_id => paaf.assignment_id, -- in number
p_aggregation => 'sum', -- in varchar2
p_round => 2 -- in number default 2
)
),
0
) funeral_cover,
ppos.actual_termination_date termination_date
from (
select ptp.payroll_id,
min(ptp.start_date) real_month_start,
max(ptp.end_date) real_month_end
from per_time_periods ptp
where decode(ptp.prd_information_category, 'ZA', to_char(ptp.pay_advice_date, 'yyyymm'), to_char(ptp.regular_payment_date, 'yyyymm')) = '201612'
group by ptp.payroll_id
) mon,
pay_all_payrolls_f payr,
per_all_assignments_f paaf,
per_periods_of_service ppos,
per_people_f papf,
per_business_groups pbg,
hr_all_organization_units haou,
per_jobs pj,
pay_cost_allocation_keyflex pcak
where payr.payroll_id = mon.payroll_id
and mon.real_month_end between payr.effective_start_date and payr.effective_end_date
and paaf.payroll_id = mon.payroll_id
and paaf.assignment_type = 'E'
and paaf.primary_flag = 'Y'
and paaf.effective_start_date =
(
select max(paaf2.effective_start_date)
from per_all_assignments_f paaf2
where paaf2.assignment_id = paaf.assignment_id
and paaf2.assignment_type = 'E'
and paaf2.primary_flag = 'Y'
and paaf2.payroll_id = mon.payroll_id
and mon.real_month_start <= paaf2.effective_end_date
and mon.real_month_end >= paaf2.effective_start_date
)
and ppos.period_of_service_id = paaf.period_of_service_id
and mon.real_month_start <= nvl(ppos.actual_termination_date, to_date('31/12/4712', 'dd/mm/yyyy'))
and mon.real_month_end >= ppos.date_start
and papf.person_id = paaf.person_id
and papf.effective_start_date =
(
select max(papf2.effective_start_date)
from per_all_people_f papf2
where papf2.person_id = paaf.person_id
and mon.real_month_start <= papf2.effective_end_date
and mon.real_month_end >= papf2.effective_start_date
)
and pbg.business_group_id = paaf.business_group_id
and haou.organization_id (+) = paaf.organization_id
and pj.job_id (+) = paaf.job_id
and pcak.cost_allocation_keyflex_id (+) = haou.cost_allocation_keyflex_id
and
(
nvl
(
xxpay_util.safe_to_number
(
xxpay_util_element.get_run_result
(
p_business_group_id => paaf.business_group_id, -- in number
p_payroll_id => paaf.payroll_id, -- in number
p_payroll_action_id => null, -- in number,
p_start_period => mon.real_month_start, -- in date
p_end_period => mon.real_month_end, -- in date
p_element_name_regex => '^Disability Cover ER$', -- in varchar2 -- Disability Cover ER Opt Out
p_input_value => 'Pay Value', -- in varchar2
p_assignment_id => paaf.assignment_id, -- in number
p_aggregation => 'sum', -- in varchar2
p_round => 2 -- in number default 2
)
),
0
)
+
nvl
(
xxpay_util.safe_to_number
(
xxpay_util_element.get_run_result
(
p_business_group_id => paaf.business_group_id, -- in number
p_payroll_id => paaf.payroll_id, -- in number
p_payroll_action_id => null, -- in number,
p_start_period => mon.real_month_start, -- in date
p_end_period => mon.real_month_end, -- in date
p_element_name_regex => '^Death Cover ER Opt Out$', -- in varchar2
p_input_value => 'Pay Value', -- in varchar2
p_assignment_id => paaf.assignment_id, -- in number
p_aggregation => 'sum', -- in varchar2
p_round => 2 -- in number default 2
)
),
0
)
+
nvl
(
xxpay_util.safe_to_number
(
xxpay_util_element.get_run_result
(
p_business_group_id => paaf.business_group_id, -- in number
p_payroll_id => paaf.payroll_id, -- in number
p_payroll_action_id => null, -- in number,
p_start_period => mon.real_month_start, -- in date
p_end_period => mon.real_month_end, -- in date
p_element_name_regex => '^Funeral Cover ER$', -- in varchar2 -- Funeral Cover ER Opt Out
p_input_value => 'Pay Value', -- in varchar2
p_assignment_id => paaf.assignment_id, -- in number
p_aggregation => 'sum', -- in varchar2
p_round => 2 -- in number default 2
)
),
0
)
) != 0
and nvl
(
xxpay_util_element.get_element_entry
(
p_business_group_id => paaf.business_group_id, -- in number
p_start_period => mon.real_month_start, -- in date
p_end_period => mon.real_month_end, -- in date
p_element_name_regex => '^Retirement Fund Opt In$', -- in varchar2
p_input_value => 'Opt In or Out', -- in varchar2
p_assignment_id => paaf.assignment_id, -- in number
p_aggregation => 'none', -- in varchar2
p_round => 0 -- in number default 2
),
'$XXX$'
) in ('NC', 'OUT')
and exists
(
select 1
from pay_payroll_actions ppap,
pay_assignment_actions paap,
pay_action_interlocks pai,
pay_assignment_actions paar,
pay_payroll_actions ppar,
per_time_periods ptp
where ppap.action_type in ('P', 'U')
and ppap.action_status = 'C'
and paap.payroll_action_id = ppap.payroll_action_id
and paap.action_status = 'C'
and pai.locking_action_id = paap.assignment_action_id
and paar.assignment_action_id = pai.locked_action_id
and ppar.payroll_action_id = paar.payroll_action_id
and ppar.action_type in ('R', 'Q')
and ptp.time_period_id = ppar.time_period_id
and decode(ptp.prd_information_category, 'ZA', to_char(ptp.pay_advice_date, 'yyyymm'), to_char(ptp.regular_payment_date, 'yyyymm')) = '201612'
and paap.assignment_id = paaf.assignment_id
and paar.assignment_id = paaf.assignment_id
)
order by pcak.segment2, papf.employee_number, paaf.assignment_number
Is there a way to rewrite the query so that the function calls from the select clause (xxpay_util_element.get_run_result) that is repeated in the where clause are not repeated and only called once?
you can try creating this sql as subquery and add where clause in parent query :
Select * from (
select
xxpay_util_element.get_run_result as get_run_result_1, --only fetch values here
.......
from .....
)
where get_run_result_1 ......... --add where clause here
Can some one help me to convert this query to linq? I dont know how to use union and then sum in linq.
SELECT Patientname, SUM(A)AS Trec
FROM (SELECT Pm.Patientname, COUNT(*)AS A
FROM Facilitycheckinholdorder Fcho
INNER JOIN Medordertype Mot ON Fcho.Orderseq = Mot.Orderseq
JOIN Patientmaster Pm ON Mot.Patientseq = Pm.Patientseq
AND Fcho.Filleddate BETWEEN '2011-09-01 00:00:00:000' AND '2012-10-16 00:00:00:000'
AND Mot.Facilityid = 139
GROUP BY Pm.Patientname
UNION ALL
SELECT Pm.Patientname, COUNT(*)AS A
FROM Rxqdeliveryholdorder Rdho
INNER JOIN Medordertype Mot ON Rdho.Orderseq = Mot.Orderseq
JOIN Patientmaster Pm ON Mot.Patientseq = Pm.Patientseq
AND Rdho.Filleddate BETWEEN '2011-09-01 00:00:00:000' AND '2012-10-16 00:00:00:000'
AND Mot.Facilityid = 139
GROUP BY Pm.Patientname
) AS Trec
GROUP BY Patientname;
In fact this is not a real question, but I've tried my best...
var lst1 =
from fhco in facilitycheckinholdorder
join mot in meordertype on mot.orderseq equals fhco.orderseq
join pm in patientmaster on mot.patientseq equals pm.patientseq
where
fcho.FilledDate >= new DateTime(2011, 9, 1)
fcho.FilledDate <= new DateTime(2012, 10, 16)
select pm;
var lst2 =
from rdho in rxqdeliveryholdorder
join mot in meordertype on rdho.orderseq equals mot.orderseq
join pm in patientmaster on moit.patientseq equals pm.patientseq
where
fcho.FilledDate >= new DateTime(2011, 9, 1)
fcho.FilledDate <= new DateTime(2012, 10, 16)
select pm;
var res =
from item in lst1.Union(lst2)
select new { Name = item.patientname, Count = lst1.Count() + lst2.Count() };
Key points:
Your outermost query seems redundant.
Your names are not common C# style, and it makes them difficult to read.
UNION ALL corresponds to Concat, not Union.
Getting the Concat out of the way early lets you streamline the query. You could do this in the SQL.
.
var result =
from order in Queryable.Concat(
FacilityCheckInHoldOrder.Select(o => new { o.OrderSeq, o.FilledDate }),
RxqDeliveryHoldOrder .Select(o => new { o.OrderSeq, o.FilledDate }))
where order.FilledDate >= new DateTime(2011, 9, 1) &&
order.FilledDate < new DateTime(2012, 10, 16)
join type in MedOrderType.Where(t => t.FacilityID == 139)
on order.OrderSeq equals type.OrderSeq
join patient in PatientMaster
on type.PatientSeq equals patient.PatientSeq
group by patient.PatientName into grp
select new
{
PatientName = grp.Key,
Trec = grp.Count()
};