write SQL join query using Querysets in Django - sql

am trying to write join query on two tables using django Queryset,so need suggestions to write
SQL join query using Querysets in Django..
here is My Query and Models of Tables
SELECT t.time, d.id2
FROM disp_b_time t JOIN disp_dispatch d ON t.id1 = d.id2
WHERE t.status = "completed" AND d.status = 0 AND d.vehicle_id =1
class B_Time(models.Model):
id1 = models.ForeignKey(Book)
dispatcher= models.ForeignKey(D)
status = models.CharField(max_length=128, choices=B_STATUS)
time = models.DateTimeField(auto_now=True, auto_now_add=True)
register = models.DateField()
modified = models.DateTimeField(auto_now=True, auto_now_add=True)
class Dispatch(models.Model):
id2 = models.ForeignKey(Book)
vehicle = models.ForeignKey(Vehicle)
driveId = models.ForeignKey(Drive)
dispId = models.ForeignKey(D)
status = models.CharField(max_length=128, choices=STATUS)
register = models.DateTimeField()
modified = models.DateTimeField(auto_now=True, auto_now_add=True)
Thanks in Advance...

d = Dipatch.objects.filter(vehicle__pk=1)\
.filter(status=0).filter(dispID__b_time__status='completed')

Why
d = Dipatch.objects.filter(vehicle__pk=1)\
.filter(status=0).filter(dispID__b_time__status='completed')
?
We can simply write it as
d = Dipatch.objects.filter(vehicle__pk=1, status=0, dispID__b_time__status='completed')

Related

Django, DRF: How do I use pagination in raw SQL queries?

I'd like to use the following raw query in a ListAPIView in the Django REST Framework.
I'm not sure how to use a raw SQL query instead of a queryset to support pagination.
I've looked into it and didn't find much that made sense to me.
If I want to use a query set, it would look like this
How do I do this if I want to use raw SQL queries?
class VideoListView(generics.ListAPIView):
queryset = Video.objects.raw(...)
serializer_class = VideoSerializer
SELECT DISTINCT "t"."id",
"t"."title",
"t"."thumbnail_url",
"t"."preview_url",
"t"."embed_url",
"t"."duration",
"t"."views",
"t"."is_public",
"t"."published_at",
"t"."created_at",
"t"."updated_at",
EXISTS
(SELECT (1) AS "a"
FROM "videos_history" U0
WHERE (U0."user_id" IS NULL
AND U0."video_id" = "t"."id")
LIMIT 1) AS "is_viewed",
EXISTS
(SELECT (1) AS "a"
FROM "videos_favorite" U0
WHERE (U0."user_id" IS NULL
AND U0."video_id" = "t"."id")
LIMIT 1) AS "is_favorited",
EXISTS
(SELECT (1) AS "a"
FROM "videos_track" U0
INNER JOIN "videos_playlist" U1 ON (U0."playlist_id" = U1."id")
WHERE (U1."is_wl"
AND U1."user_id" IS NULL
AND U0."video_id" = "t"."id")
LIMIT 1) AS "is_wl"
FROM (
(SELECT "videos_video".*
FROM "videos_video"
WHERE ("videos_video"."is_public"
AND "videos_video"."published_at" <= '2022-01-03 05:20:16.725884+00:00'
AND "videos_video"."title" LIKE '%word')
ORDER BY "videos_video"."published_at" DESC
LIMIT 20)
UNION
(SELECT "videos_video".*
FROM "videos_video"
LEFT OUTER JOIN "videos_video_tags" ON ("videos_video"."id" = "videos_video_tags"."video_id")
LEFT OUTER JOIN "videos_tag" ON ("videos_video_tags"."tag_id" = "videos_tag"."id")
WHERE ("videos_video"."is_public"
AND "videos_video"."published_at" <= '2022-01-03 05:20:16.725884+00:00'
AND "videos_tag"."name" LIKE '%word')
ORDER BY "videos_video"."published_at" DESC
LIMIT 20)
) AS t
ORDER BY "t"."published_at" DESC
LIMIT 20;
Do I need to create a custom paginator or something? I'm even more confused because I'm using LIMIT and other methods for subqueries.
--- Add models.py, etc... ---
# models.py
class Tag(models.Model):
name = models.CharField(unique=True, max_length=30)
created_at = models.DateTimeField(default=timezone.now)
...
class Video(models.Model):
title = models.CharField(max_length=300)
tags = models.ManyToManyField(Tag, blank=True)
updated_at = models.DateTimeField(auto_now=True)
...
class History(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
video = models.ForeignKey(Video, on_delete=models.CASCADE)
...
class Favorite(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE
video = models.ForeignKey(Video, on_delete=models.CASCADE)
...
class Playlist(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
is_wl = models.BooleanField(default=False, editable=False)
...
class Track(models.Model):
playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, null=True)
video = models.ForeignKey(Video, on_delete=models.CASCADE)
...
The slow queryset and SQL queries that were originally used.
Video.objects.annotate(
is_viewed=Exists(History.objects.filter(user=user, video=OuterRef("pk"))),
is_favorited=Exists(
Favorite.objects.filter(user=user, video=OuterRef("pk"))
),
is_wl=Exists(
Track.objects.filter(
playlist__user=user, playlist__is_wl=True, video=OuterRef("pk")
)
),
).filter(
Q(title__contains=value)
| Q(tags__name__contains=value)),
is_public=True,
published_at__lte=timezone.now(),
).order_by("-published_at").distinct()
SELECT DISTINCT "videos_video"."id",
"videos_video"."published_at",
EXISTS
(SELECT (1) AS "a"
FROM "videos_history" U0
WHERE (U0."user_id" IS NULL
AND U0."video_id" = "videos_video"."id")
LIMIT 1) AS "is_viewed",
EXISTS
(SELECT (1) AS "a"
FROM "videos_favorite" U0
WHERE (U0."user_id" IS NULL
AND U0."video_id" = "videos_video"."id")
LIMIT 1) AS "is_favorited",
EXISTS
(SELECT (1) AS "a"
FROM "videos_track" U0
INNER JOIN "videos_playlist" U1 ON (U0."playlist_id" = U1."id")
WHERE (U1."is_wl"
AND U1."user_id" IS NULL
AND U0."video_id" = "videos_video"."id")
LIMIT 1) AS "is_wl"
FROM "videos_video"
LEFT OUTER JOIN "videos_video_tags" ON ("videos_video"."id" = "videos_video_tags"."video_id")
WHERE ("videos_video"."is_public"
AND "videos_video"."published_at" <= '2021-12-27 13:34:29.103369+00:00'
AND ("videos_video"."title" &#~ 'word'
OR "videos_video_tags"."tag_id" IN
(SELECT U0."id"
FROM "videos_tag" U0
WHERE U0."name" &#~ 'word')))
ORDER BY "videos_video"."published_at" DESC
LIMIT 20;
If you are asking about generic PageNumberPagination from rest_framework.pagination, usually it's done this way. You make your own pagination class with default values:
class VideoPagination(PageNumberPagination):
max_page_size = 100
page_size_query_param = 'page_size'
page_size = 25
Then you just add it to your view:
class VideoListView(generics.ListAPIView):
queryset = Video.objects.all()
serializer_class = VideoSerializer
pagination_class = VideoPagination
That's all, you can use parameters page and page_size.

Updating multiple tables inside cursor not working

I have two records in a table A. This helps me to update table 2 however the update is not been applied. This is the SQL code where I added a validation section that allow me to determinate the problem.
DECLARE abc CURSOR FOR
select d.cod_suc, d.cod_ramo_comercial, d.nro_pol, d.cod_item, d.cod_ramo_tecnico, d.cod_tarifa,
d.id_stro, d.nro_stro, d.fec_hora_reclamo, d.fec_aviso, d.fec_registro, d.fec_ingreso_contable,
d.txt_place_of_accident, d.id_substro, d.txt_nombre_cober, d.txt_direccion_bien_siniestrado, d.txt_descripcion_perdida, d.txt_cheque_a_nom, d.cod_manager_code, d.importe_pago_eq
from table1 d
where d.fec_hora_reclamo between '20140801' and '20150731'
and (d.cod_suc = 2 and d.cod_ramo_comercial = 255 and d.nro_pol = 1000001 and d.cod_item = 5)
OPEN abc
FETCH abc INTO #cod_suc, #cod_ramo_comercial, #nro_pol, #cod_item, #cod_ramo_tecnico, #cod_tarifa,
#id_stro, #nro_stro, #fec_hora_reclamo, #fec_aviso, #fec_registro, #fec_ingreso_contable,
#txt_place_of_accident, #id_substro, #txt_nombre_cober, #txt_direccion_bien_siniestrado, #txt_descripcion_perdida, #txt_cheque_a_nom, #cod_manager_code, #importe_pago_eq
WHILE (##FETCH_STATUS = 0)
BEGIN
select #varIDPV = min(id_pv), #varCodTarifa = min(cod_tarifa)
from #portfolio p
where p.cod_suc = #cod_suc and p.cod_ramo_comercial = #cod_ramo_comercial and p.Poliza = #nro_pol and p.Item = #cod_item and p.cod_ramo_tecnico = #cod_ramo_tecnico
and p.[ID Incident] IS NULL
/**************************************************************************************************************
-- Validation section
-- First record:
mid(id_pv) = 100, min(cod_tarifa) = 1
-- Second record:
mid(id_pv) = 100, min(cod_tarifa) = 1
--> Should be mid(id_pv) = 100, min(cod_tarifa) = 2
*/
select min(id_pv), min(cod_tarifa)
from #portfolio p
where p.cod_suc = #cod_suc and p.cod_ramo_comercial = #cod_ramo_comercial and p.Poliza = #nro_pol and p.Item = #cod_item and p.cod_ramo_tecnico = #cod_ramo_tecnico
and p.[ID Incident] IS NULL
/**************************************************************************************************************/
update p set p.[ID Incident] = #id_stro, p.[No. Incident] = #nro_stro,
p.[Fecha Accidente] = #fec_hora_reclamo, p.[Fecha Notificacion] = #fec_aviso, p.[Fecha Registro] = #fec_registro, p.[Fecha Pago] = #fec_ingreso_contable,
p.[Lugar Accidente] = #txt_place_of_accident, p.[ID Subsiniestro] = #id_substro, p.[Cobertura Amparo] = #txt_nombre_cober, p.[Direccion Bien Siniestrado] = #txt_direccion_bien_siniestrado, p.[Descripcion Perdida] = #txt_descripcion_perdida, p.[Pago A] = #txt_cheque_a_nom, p.[Referida] = #cod_manager_code,
[Incurrido R12] = #importe_pago_eq, [Incurrido Cerrados R12] = #importe_pago_eq
from #portfolio p
where p.cod_suc = #cod_suc and p.cod_ramo_comercial = #cod_ramo_comercial and p.Poliza = #nro_pol and p.Item = #cod_item and p.cod_ramo_tecnico = #cod_ramo_tecnico
and p.[ID Incident] IS NULL and p.id_pv = #varIDPV and p.cod_tarifa = #varCodTarifa
FETCH abc INTO #cod_suc, #cod_ramo_comercial, #nro_pol, #cod_item, #cod_ramo_tecnico, #cod_tarifa,
#id_stro, #nro_stro, #fec_hora_reclamo, #fec_aviso, #fec_registro, #fec_ingreso_contable,
#txt_place_of_accident, #id_substro, #txt_nombre_cober, #txt_direccion_bien_siniestrado, #txt_descripcion_perdida, #txt_cheque_a_nom, #cod_manager_code, #importe_pago_eq
END
CLOSE abc
DEALLOCATE abc
When I see the result, only the first record is updated.
I found the problem. I forgot to add one condition more in update (inside where). Thanks for the support

Full outer join very slow

I have two tables. One is todays prices and one is yesterdays prices. There is a job which updates each table over night. Yesterdays prices is a copy of todays before it gets updated.
I am trying to create a table which shows the differences between the tables.
To do this I am using a full outer join. I am filtering down my criteria to make it faster as both tables are over 48 million rows.
My current code is like this.
WITH differ AS
(
SELECT
tAP.CustomerID, tAP.ProductID, yAP.CustomerID AS 'Yest_CustomerID', yAP.ProductID AS 'Yest_ProductID',
tAP.PDG, tAP.DiscPct1, tAP.DiscPct2,
yAP.DiscPct1 AS 'Yest_DiscPct1',
yAP.DiscPct2 AS 'Yest_DiscPct2',
CONVERT(DECIMAL(18,2),tAP.DiscPct1 - yAP.DiscPct1) AS 'DiscPct1_Difference',
CONVERT(DECIMAL(18,2),tAP.DiscPct2 - yAP.DiscPct2) AS 'DiscPct2_Difference',
tAP.internalSPANumber, yAP.internalSPANumber AS 'Yest_InternalSPANumber', tAP.SPAUniqueReference,
tAP.Project,
tAP.ExpiryDate,tAP.Subaddress, tAP.PriceType, yAP.PriceType AS 'Yest_PriceType', tAP.ListPrice,
tAP.NettPrice, yAP.NettPrice AS 'Yest_NettPrice',
CONVERT(DECIMAL(18,2),tAP.NettPrice- yAP.NettPrice) AS 'NettPrice_Difference'
FROM tbl_Prices tAP FULL OUTER JOIN tbl_Prices_Yesterday yAP ON tAP.CustomerId = yAP.CustomerID AND tAP.ProductID = yAP.ProductID
AND tAP.PDG = yAP.PDG AND tAP.Project = yAP.Project AND tAP.PriceType = yAP.PriceType
WHERE (((tAP.DiscPct1 <> yAP.DiscPct1)
OR (tAP.DiscPct2 <> yAP.DiscPct2)
OR (yAP.CustomerID IS NULL)
OR (tAP.CustomerID IS NULL)
OR (tAP.NettPrice <> yAP.NettPrice)
OR (tAP.InternalSPANumber <> yAP.InternalSPANumber))
AND
(
tAP.ProductID = '10238610' OR tAP.ProductID = '10238620'
OR tAP.ProductID = '10238621' OR tAP.ProductID = '10238687'
OR tAP.ProductID = '10238688' OR yAP.ProductID = '10238610'
OR yAP.ProductID = '10238620' OR yAP.ProductID = '10238621'
OR yAP.ProductID = '10238687' OR yAP.ProductID = '10238688')
)
)
SELECT * INTO tbl_Difference FROM differ
Anyway to make this faster?
Can you filter the 2 large tables before you try to join them using AND filter in your where?
WITH tAPcte AS
(
SELECT * -- fields you need
FROM tbl_Prices
WHERE ProductID IN ('10238610',
'10238620',
'10238621',
'10238687',
'10238688')
),
yAPcte AS
(
SELECT * -- fields you need
FROM tbl_Prices_Yesterday
WHERE ProductID IN ('10238610',
'10238620',
'10238621',
'10238687',
'10238688')
)
differ AS
(
SELECT
tAP.CustomerID, tAP.ProductID, yAP.CustomerID AS 'Yest_CustomerID', yAP.ProductID AS 'Yest_ProductID',
tAP.PDG, tAP.DiscPct1, tAP.DiscPct2,
yAP.DiscPct1 AS 'Yest_DiscPct1',
yAP.DiscPct2 AS 'Yest_DiscPct2',
CONVERT(DECIMAL(18,2),tAP.DiscPct1 - yAP.DiscPct1) AS 'DiscPct1_Difference',
CONVERT(DECIMAL(18,2),tAP.DiscPct2 - yAP.DiscPct2) AS 'DiscPct2_Difference',
tAP.internalSPANumber, yAP.internalSPANumber AS 'Yest_InternalSPANumber', tAP.SPAUniqueReference,
tAP.Project,
tAP.ExpiryDate,tAP.Subaddress, tAP.PriceType, yAP.PriceType AS 'Yest_PriceType', tAP.ListPrice,
tAP.NettPrice, yAP.NettPrice AS 'Yest_NettPrice',
CONVERT(DECIMAL(18,2),tAP.NettPrice- yAP.NettPrice) AS 'NettPrice_Difference'
FROM tAPcte tAP FULL OUTER JOIN yAPcte yAP ON tAP.CustomerId = yAP.CustomerID AND tAP.ProductID = yAP.ProductID
AND tAP.PDG = yAP.PDG AND tAP.Project = yAP.Project AND tAP.PriceType = yAP.PriceType
WHERE (((tAP.DiscPct1 <> yAP.DiscPct1)
OR (tAP.DiscPct2 <> yAP.DiscPct2)
OR (yAP.CustomerID IS NULL)
OR (tAP.CustomerID IS NULL)
OR (tAP.NettPrice <> yAP.NettPrice)
OR (tAP.InternalSPANumber <> yAP.InternalSPANumber))
)
SELECT * INTO tbl_Difference FROM differ

LINQ to Entities Right Join VB.NET

I am trying to figure out how to do a right join in vb.net I have tried several different approaches but neither works.
Dim query = From I In db.scll_label Where I.scll_transactiondate >= fromDate And I.scll_transactiondate <= toDate
Join p In db.pt_mstr.Where(Function(pt) pt.pt_domain = "mueller") On I.scll_part Equals p.pt_part
Join c In db.sclws_cfg.Where(Function(wk) wk.sclws_domain = "mueller") On I.scll_wsid Equals c.sclws_id
Select New ShiftAdjustedModel With
{.Label = I,
.TransactionDate = I.scll_transactiondate,
.PartLength = p.pt_length,
.PartNetWeight = p.pt_net_wt,
.PartDescription = p.pt_desc1,
.PartTolHigh = p.pt_tol_high,
.PartType = p.pt_part_type,
.PartUM = p.pt_um,
.ProjCode = c.sclws_proj_code,
.Site = c.sclws_site}
output sql
SELECT
[Extent1].[scll_ticket] AS [scll_ticket],
[Extent1].[scll_domain] AS [scll_domain],
[Extent1].[scll_site] AS [scll_site],
[Extent1].[scll_part] AS [scll_part],
[Extent1].[scll_qty] AS [scll_qty],
[Extent1].[scll_weight] AS [scll_weight],
[Extent1].[scll_transactiondate] AS [scll_transactiondate],
[Extent1].[scll_transactiontime] AS [scll_transactiontime],
[Extent1].[scll_shift] AS [scll_shift],
[Extent1].[scll_pcs_bundle] AS [scll_pcs_bundle],
[Extent1].[scll_bundle_lift] AS [scll_bundle_lift],
[Extent1].[scll_cust] AS [scll_cust],
[Extent1].[scll_wsid] AS [scll_wsid],
[Extent1].[scll_userid] AS [scll_userid],
[Extent1].[scll_remarks] AS [scll_remarks],
[Extent1].[scll_calc_weight] AS [scll_calc_weight],
[Extent1].[scll_total_feet] AS [scll_total_feet],
[Extent1].[scll_tolerance] AS [scll_tolerance],
[Extent1].[scll_drawlite_factor] AS [scll_drawlite_factor],
[Extent1].[scll_total_tare] AS [scll_total_tare],
[Extent1].[scll_tare_detail] AS [scll_tare_detail],
[Extent1].[scll_out_of_tolerance] AS [scll_out_of_tolerance],
[Extent1].[scll_tolerance_low] AS [scll_tolerance_low],
[Extent1].[scll_tolerance_high] AS [scll_tolerance_high],
[Extent1].[scll_std_weight] AS [scll_std_weight],
[Extent2].[pt_length] AS [pt_length],
[Extent2].[pt_net_wt] AS [pt_net_wt],
[Extent2].[pt_desc1] AS [pt_desc1],
[Extent2].[pt_tol_high] AS [pt_tol_high],
[Extent2].[pt_part_type] AS [pt_part_type],
[Extent2].[pt_um] AS [pt_um],
[Extent3].[sclws_proj_code] AS [sclws_proj_code],
[Extent3].[sclws_site] AS [sclws_site]
FROM [dbo].[scll_label] AS [Extent1]
INNER JOIN [dbo].[pt_mstr] AS [Extent2] ON [Extent1].[scll_part] = [Extent2].[pt_part]
INNER JOIN [dbo].[sclws_cfg] AS [Extent3] ON [Extent1].[scll_wsid] = [Extent3].[sclws_id]
WHERE ([Extent1].[scll_transactiondate] >= #p__linq__0) AND ([Extent1].[scll_transactiondate] <= #p__linq__1) AND ('mueller' = [Extent2].[pt_domain]) AND ('mueller' = [Extent3].[sclws_domain])
if i use this query
Dim query = From I In db.scll_label Where I.scll_transactiondate >= fromDate And I.scll_transactiondate <= toDate
Group Join p In db.pt_mstr.Where(Function(pt) pt.pt_domain = "mueller") On I.scll_part Equals p.pt_part Into parts = Group
Group Join c In db.sclws_cfg.Where(Function(wk) wk.sclws_domain = "mueller") On I.scll_wsid Equals c.sclws_id Into workstations = Group
From p In parts.DefaultIfEmpty From c In workstations.DefaultIfEmpty
Select New ShiftAdjustedModel With
{.Label = I,
.TransactionDate = I.scll_transactiondate,
.PartLength = p.pt_length,
.PartNetWeight = p.pt_net_wt,
.PartDescription = p.pt_desc1,
.PartTolHigh = p.pt_tol_high,
.PartType = p.pt_part_type,
.PartUM = p.pt_um,
.ProjCode = c.sclws_proj_code,
.Site = c.sclws_site}
i get this output
SELECT
[Extent1].[scll_ticket] AS [scll_ticket],
[Extent1].[scll_domain] AS [scll_domain],
[Extent1].[scll_site] AS [scll_site],
[Extent1].[scll_part] AS [scll_part],
[Extent1].[scll_qty] AS [scll_qty],
[Extent1].[scll_weight] AS [scll_weight],
[Extent1].[scll_transactiondate] AS [scll_transactiondate],
[Extent1].[scll_transactiontime] AS [scll_transactiontime],
[Extent1].[scll_shift] AS [scll_shift],
[Extent1].[scll_pcs_bundle] AS [scll_pcs_bundle],
[Extent1].[scll_bundle_lift] AS [scll_bundle_lift],
[Extent1].[scll_cust] AS [scll_cust],
[Extent1].[scll_wsid] AS [scll_wsid],
[Extent1].[scll_userid] AS [scll_userid],
[Extent1].[scll_remarks] AS [scll_remarks],
[Extent1].[scll_calc_weight] AS [scll_calc_weight],
[Extent1].[scll_total_feet] AS [scll_total_feet],
[Extent1].[scll_tolerance] AS [scll_tolerance],
[Extent1].[scll_drawlite_factor] AS [scll_drawlite_factor],
[Extent1].[scll_total_tare] AS [scll_total_tare],
[Extent1].[scll_tare_detail] AS [scll_tare_detail],
[Extent1].[scll_out_of_tolerance] AS [scll_out_of_tolerance],
[Extent1].[scll_tolerance_low] AS [scll_tolerance_low],
[Extent1].[scll_tolerance_high] AS [scll_tolerance_high],
[Extent1].[scll_std_weight] AS [scll_std_weight],
[Extent2].[pt_length] AS [pt_length],
[Extent2].[pt_net_wt] AS [pt_net_wt],
[Extent2].[pt_desc1] AS [pt_desc1],
[Extent2].[pt_tol_high] AS [pt_tol_high],
[Extent2].[pt_part_type] AS [pt_part_type],
[Extent2].[pt_um] AS [pt_um],
[Extent3].[sclws_proj_code] AS [sclws_proj_code],
[Extent3].[sclws_site] AS [sclws_site]
FROM [dbo].[scll_label] AS [Extent1]
LEFT OUTER JOIN [dbo].[pt_mstr] AS [Extent2] ON ('mueller' = [Extent2].[pt_domain]) AND ([Extent1].[scll_part] = [Extent2].[pt_part])
LEFT OUTER JOIN [dbo].[sclws_cfg] AS [Extent3] ON ('mueller' = [Extent3].[sclws_domain]) AND ([Extent1].[scll_wsid] = [Extent3].[sclws_id])
WHERE ([Extent1].[scll_transactiondate] >= #p__linq__0) AND ([Extent1].[scll_transactiondate] <= #p__linq__1)
I simply want a right outer join on the two tables it translated into a left outer join. Even if I start with the tables for the right join as a lot of posts have suggested I get weird sql using cross joins and unions instead of right join.

How to join three tables?

SELECT
PC_SL_ACNO, -- DB ITEM
SLNAME, -- ACCOUNT NAME:
SL_TOTAL_AMOUNT -- TOTAL AMOUNT:
FROM GLAS_PDC_CHEQUES
WHERE PC_COMP_CODE=:parameter.COMP_CODE
AND pc_bank_from = :block02.pb_bank_code
AND pc_due_date between :block01.date_from
AND :block01.date_to
AND nvl(pc_discd,'X') IN(‘X’, 'R')
GROUP BY
pc_comp_code, pc_sl_ldgr_code, pc_sl_acno
ORDER BY pc_sl_acno
ACCOUNT NAME:
BEGIN
SELECT COAD_PTY_FULL_NAME INTO :BLOCK03.SLNAME
FROM GLAS_PTY_ADDRESS,GLAS_SBLGR_MASTERS
WHERE SLMA_COMP_CODE = :PARAMETER.COMP_CODE
AND SLMA_ADDR_ID = COAD_ADDR_ID
AND SLMA_ADDR_TYPE = COAD_ADDR_TYPE
AND SLMA_ACNO = :BLOCK03.PC_SL_ACNO
AND SLMA_COMP_CODE = COAD_COMP_CODE;
EXCEPTION WHEN OTHERS THEN NULL;
END;
TOTAL AMOUNT:
BEGIN
SELECT SUM(PC_AMOUNT) INTO :SL_TOTAL_AMOUNT
FROM GLAS_PDC_CHEQUES
WHERE PC_DUE_DATE BETWEEN :BLOCK01.DATE_FROM AND :BLOCK01.DATE_TO
AND PC_BANK_FROM = :block02.PB_BANK_CODE
AND PC_SL_ACNO = :BLOCK03.PC_SL_ACNO
AND NVL(PC_DISCD,'X') = 'R'
AND PC_COMP_CODE = :PARAMETER.COMP_CODE;
EXCEPTION WHEN OTHERS THEN :block03.SL_TOTAL_AMOUNT := 0;
END;
How can I join the three tables?
You'll have to adjust depending on precisely what criteria and required fields you have for your query or queries.
SELECT
c.PC_SL_ACNO,
a.COAD_PTY_FULL_NAME,
SUM(c.PC_AMOUNT)
FROM
GLAS_PDC_CHEQUES c
LEFT JOIN
GLAS_SBLGR_MASTERS m
ON ( c.PC_SL_ACNO = m.SLMA_ACNO
AND c.PC_COMP_CODE = m.SLMA_COMP_CODE
)
LEFT JOIN
GLAS_PTY_ADDRESS a
ON ( m.SLMA_ADDR_ID = a.COAD_ADDR_ID
AND m.SLMA_COMP_CODE = a.COAD_COMP_CODE
AND m.SLMA_ADDR_TYPE = a.COAD_ADDR_TYPE
)
WHERE
c.PC_COMP_CODE = :PARAMETER.COMP_CODE
AND c.PC_SL_ACNO = :BLOCK03.PC_SL_ACNO
AND c.PC_BANK_FROM = :BLOCK02.PB_BANK_CODE
AND NVL(c.PC_DISCD,'X') IN (‘X’, 'R')
AND c.PC_DUE_DATE BETWEEN :BLOCK01.DATE_FROM AND :BLOCK01.DATE_TO
GROUP BY
c.PC_SL_ACNO, -- not sure which grouping exactly you need.
a.COAD_PTY_FULL_NAME
ORDER BY
c.PC_SL_ACNO
I notice that in the first query you have pc_comp_code as a search criterion, and on the leading edge of your grouping - is that what you need?
This is a bit of an 'estimate' due to the enigmatic nature of your question!