Related
I have an issue where I am using a query to filter my results based on the lead time of an article. The confusing part for me is there is a sub section of that where i need to filter certain articles based on lead time and the country of origin. I am trying to do this using a NOT EXISTSstatement in side of WHERE but the results don't seem to be what I would expect. For example all articles with a country of origin of HONDURAS and a lead time of 90 should not return any results with a so_conf_del_date of after 2/15/19...however in the results I get many results of dates well into march which should be excluded from what I can see. Thought I would get a different set of eyes on it as I really don't use not exists a ton. thanks.
UPDATE: changing to NOT IN from NOT EXISTS and updated the correlation. Note also the subquery performs exactly as it should so not sure why I am getting results back outside of the range
Query UPDATED:
/* What to do about multiple COO's in ONE RANGE? ...join on order ORDER_ITEM.SEASONAL_INDICATOR? */
/* Use CASE WHEN in subquery to JOIN outerquery on vw_order_item.seasonal_indicator = OneRange_NAM.SEASON */
/* Assumption is being made that 'seasonal indicator' in vw_order_item would align with 'season' and thus COO in OneRange */
/* Added Date/LeadTime Parameters */
/* Use 'Planned Delivery Time'...this includes lead time and delivery time? */
/* Right join to ONE RANGE */
/* ARUN has no fully unallocated quantities - YES IT DOES */
/* 11/12/18 - replaced RDD with CDD */
SELECT kd.business_segment_desc,
q0.plant_code,
q0.req_cat AS 'requirement_category',
m.[department],
q0.commission_code_id,
aa.LeadTime,
q0.so_conf_del_date,
q0.valid_to_date,
q0.sales_order_number,
q0.sales_order_item_number,
q0.sold_to,
q0.bill_to,
m.working_number,
q0.material,
m.[description],
q0.open_quantity,
q0.allocated_quantity,
q0.unallocated_quantity,
q0.percent_unallocated,
aa.ActivationStatus AS 'global status',
m.ib_lock,
o.country_of_origin
FROM pdx_sap_user..vw_mm_material m
JOIN pdx_sap_user..vw_kd_business_segment kd ON m.business_segment_code = kd.business_segment_code
JOIN asagdwpdx_prod..ArticleNumbers aa ON m.material = aa.ArticleNumber
JOIN adi_user_maintained..VW_ONERange_NAM o ON m.material = o.article
AND aa.ArticleNumber = o.Article
JOIN
(SELECT i.plant_code,
h.commission_code_id,
a.so_conf_del_date,
h.valid_to_date,
i.sales_order_number,
i.sales_order_item_number,
h.sold_to,
h.bill_to,
i.material,
i.open_quantity,
((i.open_quantity) - SUM(a.quantity)) AS 'allocated_quantity',
SUM(a.quantity) AS 'unallocated_quantity',
a.req_cat,
ROUND(SUM(a.quantity)/(i.open_quantity),2) AS 'percent_unallocated',
SUM(a.quantity) AS 'arun_allocated_qty',
CASE
WHEN i.seasonal_indicator = '18S'
THEN 'SS2018'
WHEN i.seasonal_indicator = '18F'
THEN 'FW2018'
WHEN i.seasonal_indicator = '19S'
THEN 'SS2019'
WHEN i.seasonal_indicator = '19F'
THEN 'FW2019'
ELSE 'NO SEASON'
END AS 'seasonal_indicator'
FROM pdx_sap_user..vw_order_item i
JOIN pdx_sap_user..vw_order_header h ON i.sales_order_number = h.sales_order_number
JOIN pdx_sap_user..vw_arun_norm_new a ON i.sales_order_number = a.sales_order_number
AND i.sales_order_item_number = a.sales_order_item_number
WHERE i.open_quantity > 0
AND h.commission_code_id = 'B'
AND a.stock_type = 'A'
GROUP BY i.plant_code,
h.commission_code_id,
a.so_conf_del_date,
h.valid_to_date,
i.sales_order_number,
i.sales_order_item_number,
h.sold_to,
h.bill_to,
i.material,
i.open_quantity,
a.req_cat,
i.unallocated_quantity,
i.seasonal_indicator
HAVING SUM((a.quantity)/i.open_quantity) > .5) q0 ON m.material = q0.material
AND q0.seasonal_indicator = o.season
WHERE aa.LeadTime = '30'
AND q0.so_conf_del_date < '01/15/2019'
OR aa.LeadTime = '45'
AND q0.so_conf_del_date < '02/01/2019'
OR aa.LeadTime = '60'
AND q0.so_conf_del_date < '02/15/2019'
OR aa.LeadTime = '75'
AND q0.so_conf_del_date < '03/01/2019'
OR aa.LeadTime = '90'
AND q0.so_conf_del_date < '03/15/2019'
OR aa.LeadTime = '105'
AND q0.so_conf_del_date < '04/01/2019'
OR aa.LeadTime = '120'
AND q0.so_conf_del_date < '04/15/2019'
OR aa.LeadTime = '135'
AND q0.so_conf_del_date < '05/01/2019'
AND q0.sales_order_number NOT IN ( SELECT q01.sales_order_number
FROM pdx_sap_user..vw_order_item q01
JOIN pdx_sap_user..vw_arun_norm_new a1 ON q01.sales_order_number = a1.sales_order_number
AND q01.sales_order_item_number = a1.sales_order_item_number
JOIN asagdwpdx_prod..ArticleNumbers aa1 ON q01.material = aa1.ArticleNumber
JOIN adi_user_maintained..VW_ONERange_NAM o1 ON q01.material = o1.article
WHERE
(
aa1.LeadTime = '30'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '12/15/2018'
)
OR
(
aa1.LeadTime = '45'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '01/01/2019'
)
OR
(
aa1.LeadTime = '60'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '01/15/2019'
)
OR
(
aa1.LeadTime = '75'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '02/01/2019'
)
OR
(
aa1.LeadTime = '90'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '02/15/2019'
)
OR
(
aa1.LeadTime = '90'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '03/01/2019'
)
OR
(
aa1.LeadTime = '105'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '03/15/2019'
)
AND q0.sales_order_number = q01.sales_order_number
AND aa.LeadTime = aa1.LeadTime
AND q0.so_conf_del_date = a1.so_conf_del_date
AND o.Country_of_Origin = o1.Country_of_Origin)
GROUP BY kd.business_segment_desc,
q0.plant_code,
q0.req_cat,
m.[department],
q0.commission_code_id,
aa.LeadTime,
q0.so_conf_del_date,
q0.valid_to_date,
q0.sales_order_number,
q0.sales_order_item_number,
q0.sold_to,
q0.bill_to,
m.working_number,
q0.material,
m.[description],
q0.open_quantity,
q0.allocated_quantity,
q0.unallocated_quantity,
q0.percent_unallocated,
aa.ActivationStatus,
m.ib_lock,
o.country_of_origin
ORDER BY q0.sales_order_number DESC;
WORKING VERSION:
/* What to do about multiple COO's in ONE RANGE? ...join on order ORDER_ITEM.SEASONAL_INDICATOR? */
/* Use CASE WHEN in subquery to JOIN outerquery on vw_order_item.seasonal_indicator = OneRange_NAM.SEASON */
/* Assumption is being made that 'seasonal indicator' in vw_order_item would align with 'season' and thus COO in OneRange */
/* Added Date/LeadTime Parameters */
/* Use 'Planned Delivery Time'...this includes lead time and delivery time? */
/* Right join to ONE RANGE */
/* ARUN has no fully unallocated quantities - YES IT DOES */
/* 11/12/18 - replaced RDD with CDD */
SELECT kd.business_segment_desc,
q0.plant_code,
q0.req_cat AS 'requirement_category',
m.[department],
q0.commission_code_id,
aa.LeadTime,
q0.so_conf_del_date,
q0.valid_to_date,
q0.sales_order_number,
q0.sales_order_item_number,
q0.sold_to,
q0.bill_to,
m.working_number,
q0.material,
m.[description],
q0.open_quantity,
q0.allocated_quantity,
q0.unallocated_quantity,
q0.percent_unallocated,
aa.ActivationStatus AS 'global status',
m.ib_lock,
o.country_of_origin
FROM pdx_sap_user..vw_mm_material m
JOIN pdx_sap_user..vw_kd_business_segment kd ON m.business_segment_code = kd.business_segment_code
JOIN asagdwpdx_prod..ArticleNumbers aa ON m.material = aa.ArticleNumber
JOIN adi_user_maintained..VW_ONERange_NAM o ON m.material = o.article
AND aa.ArticleNumber = o.Article
JOIN
(SELECT i.plant_code,
h.commission_code_id,
a.so_conf_del_date,
h.valid_to_date,
i.sales_order_number,
i.sales_order_item_number,
h.sold_to,
h.bill_to,
i.material,
i.open_quantity,
((i.open_quantity) - SUM(a.quantity)) AS 'allocated_quantity',
SUM(a.quantity) AS 'unallocated_quantity',
a.req_cat,
ROUND(SUM(a.quantity)/(i.open_quantity),2) AS 'percent_unallocated',
SUM(a.quantity) AS 'arun_allocated_qty',
CASE
WHEN i.seasonal_indicator = '18S'
THEN 'SS2018'
WHEN i.seasonal_indicator = '18F'
THEN 'FW2018'
WHEN i.seasonal_indicator = '19S'
THEN 'SS2019'
WHEN i.seasonal_indicator = '19F'
THEN 'FW2019'
ELSE 'NO SEASON'
END AS 'seasonal_indicator'
FROM pdx_sap_user..vw_order_item i
JOIN pdx_sap_user..vw_order_header h ON i.sales_order_number = h.sales_order_number
JOIN pdx_sap_user..vw_arun_norm_new a ON i.sales_order_number = a.sales_order_number
AND i.sales_order_item_number = a.sales_order_item_number
WHERE i.open_quantity > 0
AND h.commission_code_id = 'B'
AND a.stock_type = 'A'
AND i.sales_order_number NOT IN (SELECT q01.sales_order_number
FROM pdx_sap_user..vw_order_item q01
JOIN pdx_sap_user..vw_arun_norm_new a1 ON q01.sales_order_number = a1.sales_order_number
AND q01.sales_order_item_number = a1.sales_order_item_number
JOIN asagdwpdx_prod..ArticleNumbers aa1 ON q01.material = aa1.ArticleNumber
JOIN adi_user_maintained..VW_ONERange_NAM o1 ON q01.material = o1.article
WHERE
(
aa1.LeadTime = '30'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '12/15/2018'
)
OR
(
aa1.LeadTime = '45'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '01/01/2019'
)
OR
(
aa1.LeadTime = '60'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '01/15/2019'
)
OR
(
aa1.LeadTime = '75'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '02/01/2019'
)
OR
(
aa1.LeadTime = '90'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '02/15/2019'
)
OR
(
aa1.LeadTime = '90'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '03/01/2019'
)
OR
(
aa1.LeadTime = '105'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '03/15/2019'
)
AND q01.sales_order_number = i.sales_order_number)
GROUP BY i.plant_code,
h.commission_code_id,
a.so_conf_del_date,
h.valid_to_date,
i.sales_order_number,
i.sales_order_item_number,
h.sold_to,
h.bill_to,
i.material,
i.open_quantity,
a.req_cat,
i.unallocated_quantity,
i.seasonal_indicator
HAVING SUM((a.quantity)/i.open_quantity) > .5) q0 ON m.material = q0.material
AND q0.seasonal_indicator = o.season
WHERE aa.LeadTime = '30'
AND q0.so_conf_del_date < '01/15/2019'
OR aa.LeadTime = '45'
AND q0.so_conf_del_date < '02/01/2019'
OR aa.LeadTime = '60'
AND q0.so_conf_del_date < '02/15/2019'
OR aa.LeadTime = '75'
AND q0.so_conf_del_date < '03/01/2019'
OR aa.LeadTime = '90'
AND q0.so_conf_del_date < '03/15/2019'
OR aa.LeadTime = '105'
AND q0.so_conf_del_date < '04/01/2019'
OR aa.LeadTime = '120'
AND q0.so_conf_del_date < '04/15/2019'
OR aa.LeadTime = '135'
AND q0.so_conf_del_date < '05/01/2019'
GROUP BY kd.business_segment_desc,
q0.plant_code,
q0.req_cat,
m.[department],
q0.commission_code_id,
aa.LeadTime,
q0.so_conf_del_date,
q0.valid_to_date,
q0.sales_order_number,
q0.sales_order_item_number,
q0.sold_to,
q0.bill_to,
m.working_number,
q0.material,
m.[description],
q0.open_quantity,
q0.allocated_quantity,
q0.unallocated_quantity,
q0.percent_unallocated,
aa.ActivationStatus,
m.ib_lock,
o.country_of_origin
ORDER BY q0.sales_order_number DESC
Your OR is short circuiting. For example, look at this piece:
SELECT *
FROM Table
WHERE aa1.LeadTime = '30'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '12/15/2018'
OR aa1.LeadTime = '45'
Returns all records with aa1.LeadTime = '45' regardless of the other conditions.
I guess you mean this:
WHERE
(
aa1.LeadTime = '30'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '12/15/2018'
)
OR
(
aa1.LeadTime = '45'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '01/01/2019'
)
OR
(
aa1.LeadTime = '60'
AND o1.country_of_origin IN ('EL SALVADOR','HONDURAS','MEXICO','U S A' ,'GUATEMALA')
AND a1.so_conf_del_date > '01/15/2019'
)
....
....
which is a very different expression.
i have the following query.
SELECT DISTINCT datepart(day, eventdetails_datetime) as dates , bu_events.event_daysbeforeType
FROM "bu_events"
INNER JOIN "bu_eventdetails" ON "bu_eventdetails"."event_id" = "bu_events"."event_id"
WHERE "bu_events"."is_active" = 1
AND "bu_events"."is_deleted" =0
AND "bu_eventdetails"."is_active" = 1
AND "bu_eventdetails"."is_deleted" =0
AND "bu_events"."service_id" = '31'
AND (DATEDIFF(Minute, BU_EventDetails.eventDetails_datetime, '2017-07-12 10:33:19') <=0 or coalesce(event_always_available,0) = 1 )
AND
(DATEDIFF(d, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 )
AND ( select max(availabletable_amount)
from bu_availabletable
inner join bu_eventdetails on bu_eventdetails.eventdetail_id = bu_availabletable.eventdetail_id
inner join bu_eventpricegroups on bu_eventpricegroups.event_id = bu_eventdetails.event_id
where bu_availabletable.eventdetail_id = bu_eventdetails.eventdetail_id
and bu_eventpricegroups.eventpricegroup_always_available = 0 ) > 0
AND datepart(Month,eventdetails_datetime) = 07
AND datediff(d,getdate(),eventdetails_datetime)>=0
What i'm trying to do, is if bu_events.event_daysbeforeType is 1 then (DATEDIFF(d, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 ) and if it's 2 then (DATEDIFF(hour, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 )
So depending on bu_events.event_daysbeforeType i want to datediff with D or HOUR.
What i've tried so far but not working is this:
SELECT DISTINCT datepart(day, eventdetails_datetime) as dates , bu_events.event_daysbeforeType
FROM "bu_events"
INNER JOIN "bu_eventdetails" ON "bu_eventdetails"."event_id" = "bu_events"."event_id"
WHERE "bu_events"."is_active" = 1
AND "bu_events"."is_deleted" =0
AND "bu_eventdetails"."is_active" = 1
AND "bu_eventdetails"."is_deleted" =0
AND "bu_events"."service_id" = '31'
AND (DATEDIFF(Minute, BU_EventDetails.eventDetails_datetime, '2017-07-12 10:33:19') <=0 or coalesce(event_always_available,0) = 1 )
AND
CASE
WHEN bu_events.event_daysbeforeType = 1 THEN
(DATEDIFF(d, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 )
ELSE
(DATEDIFF(hour, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 )
END
AND ( select max(availabletable_amount)
from bu_availabletable
inner join bu_eventdetails on bu_eventdetails.eventdetail_id = bu_availabletable.eventdetail_id
inner join bu_eventpricegroups on bu_eventpricegroups.event_id = bu_eventdetails.event_id
where bu_availabletable.eventdetail_id = bu_eventdetails.eventdetail_id
and bu_eventpricegroups.eventpricegroup_always_available = 0 ) > 0
AND datepart(Month,eventdetails_datetime) = 07
AND datediff(d,getdate(),eventdetails_datetime)>=0
Any ideas what i'm doing wrong ?
You can't use case like you this. case is an expression, and you try to use it as flow control.
From MSDN:
The CASE expression cannot be used to control the flow of execution of Transact-SQL statements, statement blocks, user-defined functions, and stored procedures. For a list of control-of-flow methods, see Control-of-Flow Language (Transact-SQL).
Instead of using case, do this:
AND
(
(
bu_events.event_daysbeforeType = 1
AND (DATEDIFF(d, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 )
)
OR
(
bu_events.event_daysbeforeType <> 1
AND (DATEDIFF(hour, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 )
)
)
CASE is for computing the value and as SQL has no logical (boolean) values it shouldn't be mixed up with logical expressions but a computed value is a valid argument of logical expression. Try
AND (CASE WHEN bu_events.event_daysbeforeType = 1
THEN (DATEDIFF(d, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime)
ELSE DATEDIFF(hour, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime)
END >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1
)
I wrote following sql query for a report.
Select AT.OTHER_GL_CODE As ACC,
GL.GL_ID,
GL.GL_NAME,
(Case When (
AT.OTHER_TRN_DEC = 'Cash'
And AT.OTHER_CR_DR = 'CR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'CASHCR',
(Case When (
AT.OTHER_TRN_DEC = 'Cash'
And AT.OTHER_CR_DR = 'DR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'CASHDR',
(Case When (
AT.OTHER_TRN_DEC <> 'Cash'
And AT.OTHER_CR_DR = 'CR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'OTHERCR',
(Case When (
AT.OTHER_TRN_DEC <> 'Cash'
And AT.OTHER_CR_DR = 'DR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'OTHERDR',
AT.OTHER_BRN_CODE BRNCODE,
(
Select Sum( Case When TR.CR_DR = 'DR'
And TR.BRANCH_CODE = 1000
And TR.TRAN_DATE < '2017-07-01' Then TR.GL_TRN_AMT
Else 0
End
)
From COREBANKER1.dbo.GL_DAILY_TRN As TR
Where TR.GL_CODE = AT.OTHER_GL_CODE
) As DRBRFORE,
(
Select Sum( Case When TR.CR_DR = 'CR'
And TR.BRANCH_CODE = 1000
And TR.TRAN_DATE < '2017-07-01' Then TR.GL_TRN_AMT
Else 0
End
)
From COREBANKER1.dbo.GL_DAILY_TRN As TR
Where TR.GL_CODE = AT.OTHER_GL_CODE
) As CRBRFORE
From COREBANKER1.dbo.MAIN_OTHER_TRN As AT,
COREBANKER1.dbo.GL_MAIN As GL
Where AT.OTHER_BRN_CODE = 1000
And GL.GL_ID = AT.OTHER_GL_CODE
And AT.OTHER_BANK_DATE
Between '2017-07-01' And '2017-07-30';
this is the output
but my desired output is here
So how I change my query for desired result(grouping to ACC and GL_ID)?
The quick and dirty approach is to wrap the entire query and group by, this would prevent duplicate values in your 3,4,5, 6th columns.
The cleaner approach would be to take those 4 columns and wrap each one in a Select SUM(...) as you did for the later columns.
In short, no GROUP BY will leave you with duplicates - I took the liberty of giving you the syntax for the quick and dirty approach, see below.
SELECT
ACC
,GL_ID
,GL_NAME
,SUM(CASHCR) AS CASHCR
,SUM(CASHDR) AS CASHDR
,SUM(OTHERCR) AS OTHERCR
,SUM(OTHERDR) AS OTHERDR
,BRNCODE
,DRBRFORE
,CRBRFORE
FROM (
Select AT.OTHER_GL_CODE As ACC,
GL.GL_ID,
GL.GL_NAME,
(Case When (
AT.OTHER_TRN_DEC = 'Cash'
And AT.OTHER_CR_DR = 'CR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'CASHCR',
(Case When (
AT.OTHER_TRN_DEC = 'Cash'
And AT.OTHER_CR_DR = 'DR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'CASHDR',
(Case When (
AT.OTHER_TRN_DEC <> 'Cash'
And AT.OTHER_CR_DR = 'CR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'OTHERCR',
(Case When (
AT.OTHER_TRN_DEC <> 'Cash'
And AT.OTHER_CR_DR = 'DR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'OTHERDR',
AT.OTHER_BRN_CODE BRNCODE,
(
Select Sum( Case When TR.CR_DR = 'DR'
And TR.BRANCH_CODE = 1000
And TR.TRAN_DATE < '2017-07-01' Then TR.GL_TRN_AMT
Else 0
End
)
From COREBANKER1.dbo.GL_DAILY_TRN As TR
Where TR.GL_CODE = AT.OTHER_GL_CODE
) As DRBRFORE,
(
Select Sum( Case When TR.CR_DR = 'CR'
And TR.BRANCH_CODE = 1000
And TR.TRAN_DATE < '2017-07-01' Then TR.GL_TRN_AMT
Else 0
End
)
From COREBANKER1.dbo.GL_DAILY_TRN As TR
Where TR.GL_CODE = AT.OTHER_GL_CODE
) As CRBRFORE
From COREBANKER1.dbo.MAIN_OTHER_TRN As AT,
COREBANKER1.dbo.GL_MAIN As GL
Where AT.OTHER_BRN_CODE = 1000
And GL.GL_ID = AT.OTHER_GL_CODE
And AT.OTHER_BANK_DATE
Between '2017-07-01' And '2017-07-30'
)A
GROUP BY
ACC
,GL_ID
,GL_NAME
,CASHCR
,CASHDR
,OTHERCR
,OTHERDR
,BRNCODE
,DRBRFORE
,CRBRFORE
;
You could surround your query with a CTE then aggregate the fields you require.
WITH this as
(
Select AT.OTHER_GL_CODE As ACC,
GL.GL_ID,
GL.GL_NAME,
(Case When (
AT.OTHER_TRN_DEC = 'Cash'
And AT.OTHER_CR_DR = 'CR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'CASHCR',
(Case When (
AT.OTHER_TRN_DEC = 'Cash'
And AT.OTHER_CR_DR = 'DR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'CASHDR',
(Case When (
AT.OTHER_TRN_DEC <> 'Cash'
And AT.OTHER_CR_DR = 'CR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'OTHERCR',
(Case When (
AT.OTHER_TRN_DEC <> 'Cash'
And AT.OTHER_CR_DR = 'DR'
) Then AT.OTHER_AMOUNT
Else '0'
End
) As 'OTHERDR',
AT.OTHER_BRN_CODE BRNCODE,
(
Select Sum( Case When TR.CR_DR = 'DR'
And TR.BRANCH_CODE = 1000
And TR.TRAN_DATE < '2017-07-01' Then TR.GL_TRN_AMT
Else 0
End
)
From COREBANKER1.dbo.GL_DAILY_TRN As TR
Where TR.GL_CODE = AT.OTHER_GL_CODE
) As DRBRFORE,
(
Select Sum( Case When TR.CR_DR = 'CR'
And TR.BRANCH_CODE = 1000
And TR.TRAN_DATE < '2017-07-01' Then TR.GL_TRN_AMT
Else 0
End
)
From COREBANKER1.dbo.GL_DAILY_TRN As TR
Where TR.GL_CODE = AT.OTHER_GL_CODE
) As CRBRFORE
From COREBANKER1.dbo.MAIN_OTHER_TRN As AT,
COREBANKER1.dbo.GL_MAIN As GL
Where AT.OTHER_BRN_CODE = 1000
And GL.GL_ID = AT.OTHER_GL_CODE
And AT.OTHER_BANK_DATE
Between '2017-07-01' And '2017-07-30';
)
)
SELECT ACC ,GL_ID ,GL_NAME, SUM(CASHCR) AS CASHCR ,SUM(CASHDR) AS CASHDR ,SUM(OTHERCR) AS OTHERCR ,SUM(OTHERDR) AS OTHERDR, BRNCODE, DRBRFORE, CRBRFORE
FROM this
GROUP BY ACC ,GL_ID ,GL_NAME /*,CASHCR ,CASHDR ,OTHERCR ,OTHERDR */,BRNCODE
,DRBRFORE ,CRBRFORE
We have a complex sql query with five subquerys and the group by clause. If I restrict the database server cache to 16m (with the option "-ch 16m") we get randomized different results from the same sql query (these issue is reproducible on different machines). Our customer have the same issue on his system without reducing the cache with the -ch option and with 8g of free memory.
What is a possible explanation for such a behavior?
We think that it would be better to get a warning message or a database server crash than inconsistent results.
DB-Version: 11.0.1.2744
DB-Size: ~1g
We tested it also with the newest 11.0.1.XXXX EBF release.
Here the sql:
SELECT (select year(beginnt) * 100 + month ( beginnt ) FROM geschaeftsjahr WHERE beginnt <= '2012-06-30' and
endet >= '2012-06-30' and
mandant_nr = i1_mandant_nr) geschaeftsjahresbeginn_vorjahr_yyyymm,
(select beginnt from geschaeftsjahr where beginnt <= '2012-06-30' and
endet >= '2012-06-30' and
mandant_nr = i1_mandant_nr) geschaeftsjahresbeginn_vorjahr_datum,
(select year(beginnt) * 100 + month ( beginnt ) from geschaeftsjahr where beginnt <= '2013-06-30' and
endet >= '2013-06-30' and
mandant_nr = i1_mandant_nr) geschaeftsjahresbeginn_yyyymm,
(select beginnt from geschaeftsjahr where beginnt <= '2013-06-30' and
endet >= '2013-06-30' and
mandant_nr = i1_mandant_nr) geschaeftsjahresbeginn_datum,
"v_kostenstellenplan"."ks1_kstnummer",
"v_kostenstellenplan"."ks1_bezeichnung",
isnull(sum ( if ksb1_jahr*100+ksb1_monat >= year('2013-06-01')*100+month('2013-06-01') then if not isnull("bereich",'') = 'C' then "ksb1_betrag" else 0 endif else 0 endif * get_vorzeichen_kore(ksb1_mandant_nr,
ksb1_kontonummer)) ,0) "betrag_kosten",
isnull(sum ( if ksb1_jahr*100+ksb1_monat >= year('2013-06-01')*100+month('2013-06-01') then if isnull("bereich",'') = 'C' then "ksb1_betrag" else 0 endif else 0 endif * get_vorzeichen_kore(ksb1_mandant_nr,
ksb1_kontonummer)) ,0) "betrag_ertrag",
betrag_kosten + betrag_ertrag "betrag",
isnull(sum ( if ksb1_jahr*100+ksb1_monat >= year('2013-06-01')*100+01 then if not isnull("bereich",'') = 'C' then "ksb1_betrag" else 0 endif else 0 endif * get_vorzeichen_kore(ksb1_mandant_nr,
ksb1_kontonummer)) ,0) "betrag_kosten_jahresbeginn",
isnull(sum ( if ksb1_jahr*100+ksb1_monat >= year('2013-06-01')*100+01 then if isnull("bereich",'') = 'C' then "ksb1_betrag" else 0 endif else 0 endif * get_vorzeichen_kore(ksb1_mandant_nr,
ksb1_kontonummer)) ,0) "betrag_ertrag_jahresbeginn",
betrag_kosten_jahresbeginn + betrag_ertrag_jahresbeginn "betrag_jahresbeginn",
isnull(sum ( if not isnull("bereich",'') = 'C' then if isnull("ks1_kumulation",'g') = 'a' then /*seit auftragsbeginn*/ "ksb1_betrag" else /*seit Jahresbeginn*/ if ksb1_jahr*100+ksb1_monat >= year('2013-06-01')*100+01 then "ksb1_betrag" else 0 endif endif else 0 endif * get_vorzeichen_kore(ksb1_mandant_nr,
ksb1_kontonummer)) ,0) "betrag_kosten_baubeginn",
isnull(sum ( if isnull("bereich",'') = 'C' then if isnull("ks1_kumulation",'g') = 'a' then /*seit auftragsbeginn*/ "ksb1_betrag" else /*nur Vorjahreszahlen*/ if ksb1_jahr*100+ksb1_monat >= year('2013-06-01')*100+01 then "ksb1_betrag" else 0 endif endif else 0 endif * get_vorzeichen_kore(ksb1_mandant_nr,
ksb1_kontonummer)) ,0) "betrag_ertrag_baubeginn",
betrag_kosten_baubeginn + betrag_ertrag_baubeginn "betrag_baubeginn",
isnull(sum ( "ksb1_betrag" ),0) "betrag_vorjahr",
count() count,
"i_daten"."i1_name",
"i_daten"."i1_mandant_nr",
"i_daten"."i1f1_zahlenformat_auswertung",
isnull(v_kostenstellenplan.ks1_inaktiv,
'n' ) kst_inaktiv,
"v_kostenstellenplan"."kl_nr1",
"v_kostenstellenplan"."kl_bez1",
"v_kostenstellenplan"."kl_bez_ergebnis1",
"v_kostenstellenplan"."kl_nr2",
"v_kostenstellenplan"."kl_bez2",
"v_kostenstellenplan"."kl_bez_ergebnis2",
"v_kostenstellenplan"."kl_nr3",
"v_kostenstellenplan"."kl_bez3",
"v_kostenstellenplan"."kl_bez_ergebnis3",
"v_kostenstellenplan"."kl_nr4",
"v_kostenstellenplan"."kl_bez4",
"v_kostenstellenplan"."kl_bez_ergebnis4",
"v_kostenstellenplan"."kl_nrn",
"v_kostenstellenplan"."ks1_typ",
"v_kostenstellenplan"."ks1_kumulation",
isnull((select k.ks1_verantwortlicher from kostenstelle k where k.ks1_kstnummer = "v_kostenstellenplan"."ks1_kstnummer" and
k.ks1_mandant_nr = "v_kostenstellenplan"."ks1_mandant_nr"),'') kst_verantwortlicher FROM "v_kostenstellenplan" join "konto_kst_statistik_budget" on "v_kostenstellenplan"."ks1_mandant_nr" = "konto_kst_statistik_budget"."ksb1_mandant_nr" and
"v_kostenstellenplan"."ks1_kstnummer" = "konto_kst_statistik_budget"."ksb1_kostenstelle" and
"v_kostenstellenplan"."kl1_typ" = 'ks2' join "konto" on "konto"."kontonummer" = "konto_kst_statistik_budget"."ksb1_kontonummer" and
"konto"."mandant_nr" = "konto_kst_statistik_budget"."ksb1_mandant_nr" join "i_daten" on "konto"."mandant_nr" = "i_daten"."i1_mandant_nr" where not ksb1_quelle = string(char(70),
char(51)) and
not "left"(ksb1_quelle,1) = CHAR(66) and
string('D1;D2;D3;F1;F2;F4;F5;F50;F51;F52;K1;K2;L1;N1;N2;N3;N4;N5;O1;O2;P1;',
'F20;F21;F23;') like string(char(37),ksb1_quelle,
char(59) ,
char(37)) and
/*Seit Baubeginn oder Geschäftsjahresbeginn*/ ksb1_jahr*100+ksb1_monat >= if isnull("v_kostenstellenplan"."ks1_kumulation",'g') = 'a' then 0 else year('2012-06-01')*100+month('2012-06-01') end if and
ksb1_jahr*100+ksb1_monat <= year('2013-06-30')*100+month('2013-06-30') and
"kontonummer" not in (907010,997010,907011,997011 ) and
ks1_kstnummer in (select kk.kk1_kostenstelle from kostenstelle_Klassierung kk join klassierung_typ on kk1_typ = kt1_typ join klassierung on kl1_id = kk1_klassierung_id where kk1_mandant_nr = isnull(i1_kostenstellen_vererben_von_mandant_nr,
i1_mandant_nr) and
kk1_typ = 'kst' and
kl1_nummer >= '7150' and
kl1_nummer <= '7150' ) and
i1_mandant_nr in (13) GROUP BY "v_kostenstellenplan"."ks1_kstnummer",
"v_kostenstellenplan"."ks1_bezeichnung",
"i_daten"."i1_name",
"i_daten"."i1_mandant_nr",
"i_daten"."i1f1_zahlenformat_auswertung",
"v_kostenstellenplan"."ks1_inaktiv",
"v_kostenstellenplan"."kl_nr1",
"v_kostenstellenplan"."kl_bez1",
"v_kostenstellenplan"."kl_bez_ergebnis1",
"v_kostenstellenplan"."kl_nr2",
"v_kostenstellenplan"."kl_bez2",
"v_kostenstellenplan"."kl_bez_ergebnis2",
"v_kostenstellenplan"."kl_nr3",
"v_kostenstellenplan"."kl_bez3",
"v_kostenstellenplan"."kl_bez_ergebnis3",
"v_kostenstellenplan"."kl_nr4",
"v_kostenstellenplan"."kl_bez4",
"v_kostenstellenplan"."kl_bez_ergebnis4",
"v_kostenstellenplan"."kl_nrn",
"v_kostenstellenplan"."ks1_typ",
"v_kostenstellenplan"."ks1_kumulation",
ks1_mandant_nr HAVING ( "betrag_kosten" <> 0 OR "betrag_ertrag" <> 0 OR "betrag" <> 0 OR "betrag_kosten_jahresbeginn" <> 0 OR "betrag_ertrag_jahresbeginn" <> 0 OR "betrag_jahresbeginn" <> 0 OR "betrag_kosten_baubeginn" <> 0 OR "betrag_ertrag_baubeginn" <> 0 ) ORDER BY i_daten.i1_mandant_nr,
"v_kostenstellenplan"."kl_nr1",
"v_kostenstellenplan"."kl_nr2",
"v_kostenstellenplan"."kl_nr3",
"v_kostenstellenplan"."kl_nr4",
"ks1_kstnummer"
The column "betrag_kosten" for example delivers different results (see the printscreen).
I have a table where I would like to have one field (account) always shown then subqueries for counts or sums with criteria.
Example:
select ndhist_acct_nbr,
(select count(ndhist_acct_nbr) from dbo.nd_history where ndhist_type = '30'
and ndhist_rsn = '0' and ndhist_trcd = 'NF*' and ndhist_ref_type = '0' and ndhist_dt >= '03/01/2013') as NSF_TOTAL,
(select sum(ndhist_amt) from dbo.nd_history where ndhist_type = '30'
and ndhist_rsn = '98' and ndhist_trcd = 'TW0' and ndhist_ref_type = '11' and ndhist_dt >= '03/01/2013') as SIG_SPEND,
(select count(ndhist_acct_nbr) from dbo.nd_history where ndhist_type = '30'
and ndhist_rsn = '23' and ndhist_trcd = 'TW0' and ndhist_ref_type = '11' and ndhist_dt >= '03/01/2013') as PIN_TRANS,
(select count(ndhist_acct_nbr) from dbo.nd_history where ndhist_type = '30'
and ndhist_rsn = '21' and ndhist_trcd = 'SC*' and ndhist_ref_type = '0' and ndhist_dt >= '03/01/2013') as FOREIGN_AMT_FEE
from dbo.nd_history
group by ndhist_acct_nbr
The problem is the results - all of the account numbers show up but the counts/sum fields all repeat the data. Any help would be awesome!
Your subqueries are standalone - they don't depend on ndhist_acct_nbr field in any way, so the result is always the same.
Besides, this technique (using this many subqueries for every row of output) is a bad idea.
You should simplify the query, and instead of count distinct and subqueries, make sum(case when ... clauses.
Try:
select ndhist_acct_nbr,
count(case when ndhist_type = '30' and ndhist_rsn = '0' and ndhist_trcd = 'NF*' and ndhist_ref_type = '0' and ndhist_dt >= '03/01/2013'
then ndhist_acct_nbr end) as NSF_TOTAL,
sum(case when ndhist_type = '30' and ndhist_rsn = '98' and ndhist_trcd = 'TW0' and ndhist_ref_type = '11' and ndhist_dt >= '03/01/2013'
then ndhist_amt end) as SIG_SPEND,
count(case when ndhist_type = '30' and ndhist_rsn = '23' and ndhist_trcd = 'TW0' and ndhist_ref_type = '11' and ndhist_dt >= '03/01/2013'
then ndhist_acct_nbr end) as PIN_TRANS,
count(case when ndhist_type = '30' and ndhist_rsn = '21' and ndhist_trcd = 'SC*' and ndhist_ref_type = '0' and ndhist_dt >= '03/01/2013'
then ndhist_acct_nbr end) as FOREIGN_AMT_FEE
from dbo.nd_history
group by ndhist_acct_nbr
You can use derived columns from the results by putting the whole query inside an inline query and then selecting from it - like so:
select sq.*,
NSF_TOTAL*5 + SIG_SPEND*0.10 + PIN_TRANS*0.05 + FOREIGN_ATM_FEE as TOTAL_INCOME
from
(select ndhist_acct_nbr,
count(case when ndhist_type = '30' and ndhist_rsn = '0' and ndhist_trcd = 'NF*' and ndhist_ref_type = '0' and ndhist_dt >= '03/01/2013'
then ndhist_acct_nbr end) as NSF_TOTAL,
sum(case when ndhist_type = '30' and ndhist_rsn = '98' and ndhist_trcd = 'TW0' and ndhist_ref_type = '11' and ndhist_dt >= '03/01/2013'
then ndhist_amt end) as SIG_SPEND,
count(case when ndhist_type = '30' and ndhist_rsn = '23' and ndhist_trcd = 'TW0' and ndhist_ref_type = '11' and ndhist_dt >= '03/01/2013'
then ndhist_acct_nbr end) as PIN_TRANS,
count(case when ndhist_type = '30' and ndhist_rsn = '21' and ndhist_trcd = 'SC*' and ndhist_ref_type = '0' and ndhist_dt >= '03/01/2013'
then ndhist_acct_nbr end) as FOREIGN_AMT_FEE
from dbo.nd_history
group by ndhist_acct_nbr) sq
This could be done more elegantly via a CTE if you are using a RDBMS (such as Oracle, PostgreSQL or SQLServer) that supports CTEs.