Getting product join issue - teradata

i have one query which is doing a product join because there is join condition missing in the LOJ. Could you guys help me find an alternative to the below:
SELECT DISTINCT
1 AS ARRANGEMENT_ID
,AR.ARRANGEMENT_TYPE_ID
,TRIM(LEADING '0' FROM SRC.QCA_KB_ACCT_NBR) AS UNIQUE_ID_IN_SOURCE_SYSTEM
,NULL AS AR_OPEN_DATE
,NULL AS AR_CLOSED_DATE
,NULL AS AR_LCS_DATE
,-3 AS AR_LCS_TYPE_ID
,CPT.PRODUCT_TYPE_ID
,-3 AS SUB_PRODUCT_TYPE_ID
,NULL AS REPRESENTING_ORG_UNIT_ID
,-3 AS AR_BRAND_TYPE_ID
,NULL AS INITIATING_IP_ID
,-3 AS CLOSED_REASON_TYPE_ID
,-3 AS GL_SBU_TYPE_ID
,-3 AS AR_PAYMENT_TYPE_ID
,-3 AS AR_STRUCTURE_TYPE_ID
,SRC.EFFECTIVE_START_DATE
,SRC.EFFECTIVE_END_DATE
,'ZAF'
,'40' AS FILE_ID
,'' AS ETL_PROCESS_ID
,CURRENT_TIMESTAMP(6) AS DW_LOAD_TIMESTAMP
,NULL AS DW_UPD_LOAD_TIMESTAMP
FROM Y.T_Q18000_ACCOUNT_MASTER_INT SRC
LEFT OUTER JOIN X.ARRANGEMENT_TYPE AR
ON AR.ARRANGEMENT_TYPE_DESC = 'Account Arrangement'
LEFT OUTER JOIN X.COMBD_PRODUCT_TYPE CPT
ON CPT.ORIGINAL_LOOKUP_TABLE_NAME = 'PRODUCT'
AND CPT.PRODUCT_TYPE_CODE = 'CARD'
AND CPT.PRODUCT_TYPE_DESC = 'Card'
AND CPT.EFFECTIVE_END_DATE = '3499-12-31'
It's throwing no more room in database.
Should i go for inline query here. I dont have a joining condition for other table.
Regards,
Amit

Are you sure this query will return what you want?
Do to the missing join-conditions you actually CROSS JOIN all rows from both ARRANGEMENT_TYPE and COMBD_PRODUCT_TYPE to T_Q18000_ACCOUNT_MASTER_INT (and DISTINCT seems to cure the effect, but not the cause).
Try to join to Dervied Tables instead:
FROM Y.T_Q18000_ACCOUNT_MASTER_INT SRC
CROSS JOIN
(
SELECT *
FROM X.ARRANGEMENT_TYPE
WHERE ARRANGEMENT_TYPE_DESC = 'Account Arrangement'
) AS AR
CROSS JOIN
(
SELECT *
FROM X.COMBD_PRODUCT_TYPE
WHERE ORIGINAL_LOOKUP_TABLE_NAME = 'PRODUCT'
AND PRODUCT_TYPE_CODE = 'CARD'
AND PRODUCT_TYPE_DESC = 'Card'
AND EFFECTIVE_END_DATE = '3499-12-31'
) AS CPT
Hopefully those Derived Table return a small number of rows...
If those Selects actually return a single row you might replace them by a Scalar Subquery, this should access both tables with a "Dispatcher Retrieve Step" and a single table scan without any joins:
SELECT DISTINCT -- distinct probably no longer needed
1 AS ARRANGEMENT_ID
, (
SELECT ARRANGEMENT_TYPE_ID
FROM X.ARRANGEMENT_TYPE
WHERE ARRANGEMENT_TYPE_DESC = 'Account Arrangement'
) AS ARRANGEMENT_TYPE_ID
,TRIM(LEADING '0' FROM SRC.QCA_KB_ACCT_NBR) AS UNIQUE_ID_IN_SOURCE_SYSTEM
,NULL AS AR_OPEN_DATE
,NULL AS AR_CLOSED_DATE
,NULL AS AR_LCS_DATE
,-3 AS AR_LCS_TYPE_ID
, (
SELECT PRODUCT_TYPE_ID
FROM X.COMBD_PRODUCT_TYPE
WHERE ORIGINAL_LOOKUP_TABLE_NAME = 'PRODUCT'
AND PRODUCT_TYPE_CODE = 'CARD'
AND PRODUCT_TYPE_DESC = 'Card'
AND EFFECTIVE_END_DATE = '3499-12-31'
) AS PRODUCT_TYPE_ID
,-3 AS SUB_PRODUCT_TYPE_ID
,NULL AS REPRESENTING_ORG_UNIT_ID
,-3 AS AR_BRAND_TYPE_ID
,NULL AS INITIATING_IP_ID
,-3 AS CLOSED_REASON_TYPE_ID
,-3 AS GL_SBU_TYPE_ID
,-3 AS AR_PAYMENT_TYPE_ID
,-3 AS AR_STRUCTURE_TYPE_ID
,SRC.EFFECTIVE_START_DATE
,SRC.EFFECTIVE_END_DATE
,'ZAF'
,'40' AS FILE_ID
,'' AS ETL_PROCESS_ID
,CURRENT_TIMESTAMP(6) AS DW_LOAD_TIMESTAMP
,NULL AS DW_UPD_LOAD_TIMESTAMP
FROM Y.T_Q18000_ACCOUNT_MASTER_INT AS SRC

Related

Oracle 11x Newbie - simple, but sincere...

First, thank you for taking the time to read this, I am fairly well experienced with most versions of MSSQL, but not so much with Oracle and PL SQL.
My problem and question are this:
I have a SSRS report in MSSQK2k12 that is calling a stored proc on an Oracle 11x db. there are several params passed in that are used in the where clause, I need to add one more param ( a simple Y/N) that will add additional filters to the where clause, effectively saying at the report prompt 'do you want to see all parts? (Y/N). A 'Y' answer will run the proc nearly wide open, including parts that have no inventory, parts on hand, but already sold, parts no longer active. A 'N' response will pass filters that require available inventory, valid current part class, etc.
I have attempted a half-dozen seemingly good solutions, to no avail. I have asked an associate (who is well versed in PLSQL) for his advice, his resulting 'DECODE' addition did nothing. I would like to request advice/assistance that does not involve months of study, as I only have a few days to finish. Please note, the original SP was not my work, I have inherited from predecessor would did/could not complete. Stored procedure (Scrubbed) attached
CREATE OR REPLACE PROCEDURE ORACLE_PROD.RPT_LIKE_PARTS_TEST (
p_Pos1 IN varchar2
, p_Description IN varchar2
, p_StartPos IN varchar2
, p_StartPosValue IN varchar2
, p_ViewAll IN varchar2 --ADDED to allow filtered return for data
, p_recordset OUT SYS_REFCURSOR)
AS
BEGIN
OPEN p_recordset FOR
SELECT T1.ITEM
, T1.REVISION
, T1.DESCRIPTION
, T2.CCN
, T2.DELETED
, T2.OBSOLETED
, T2.FINGOOD
, T2.ABC
, T3.MAS_LOC
, T3.LOCATION
, (T3.OH_QTY - T3.COM_QTY) - T3.RESV_QTY as Avail_QTY
, T1.USER_NUM1
, case when T2.HALT<>' ' then 'Y' else NULL end as Halt
, T4.DESCRIPTION as T4_Description
, det.OH_QTY as Det_OH_QTY
, det.COM_QTY as Det_COM_QTY
, DECODE(det.INSP_STAT,'3','Passed Inpection' ,DECODE det.INSP_STAT,'1','Waiting Inspection' ,' ')) as Inspect_Descr
, T3.RESV_QTY
from ITEM T1
LEFT OUTER JOIN ITEM_CCN T2
ON T1.ITEM=T2.ITEM
and T1.REVISION=T2.REVISION
LEFT OUTER JOIN ITEM_LOC T3
on T2.CCN=T3.CCN
and T2.ITEM=T3.ITEM
and T2.REVISION=T3.REVISION
LEFT OUTER JOIN HALT T4
on T2.HALT=T4.HALT
and T2.CCN=T4.CCN
LEFT OUTER JOIN ITEM_DET det
on T3.CCN=det.CCN
and T3.ITEM=det.ITEM
and T3.REVISION=det.REVISION
and T3.MAS_LOC=det.MAS_LOC
and T3.LOCATION=det.LOCATION
where T2.OBSOLETED is null
--** all commented parts are attempted adds
--&&&and CASE (p_ViewAll)
--&&& when 'N'
--&&& THEN --T2.HALT = DECODE(T2.HALT,'DSGN', 'XXX',' ','XXX',T2.HALT)
-- and
--&&& (T2.HALT != 'DSGN' and (((T3.OH_QTY - T3.COM_QTY) - T3.RESV_QTY))> 0
--and T2.HALT <> 'DSGN' and T3.mas_loc <>'99' and T3.mas_loc <>' '
--&&&WHEN 'Y'
--&&& THEN
and T2.HALT <>'DSGN'
--&&&ELSE NULL-- or T3.mas_loc <> '')
--&&&END
--**
/*and T2.HALT = decode(p_ViewAll,'Y',
DECODE(T2.HALT,'DSGN', T2.HALT),
DECODE(T2.HALT,'DSGN', T2.HALT)
--DECODE(T2.HALT,'DSGN', 'XXX',' ','XXX',T2.HALT),
--DECODE(T2.HALT,'DSGN', 'XXX', T2.HALT)
)
and (p_ViewAll != 'Y' or T3.mas_loc not in ('99',' '))*/
--**
AND UPPER(TRIM(T1.ITEM)) LIKE (CASE WHEN LENGTH(TRIM(p_pos1)) > 0 THEN UPPER(TRIM(p_pos1) || '%') ELSE UPPER(TRIM(T1.ITEM))END)
AND UPPER(T1.DESCRIPTION) LIKE (CASE WHEN LENGTH(p_Description) > 0 THEN UPPER(('%' || p_Description || '%')) ELSE UPPER(UPPER(T1.DESCRIPTION))END)
AND
(CASE WHEN TO_NUMBER(NVL(TRIM(p_StartPos),'0')) > 0 THEN SUBSTR(TRIM(T1.ITEM),TO_NUMBER(TRIM(p_StartPos)),NVL(LENGTH(UPPER(TRIM(p_StartPosValue))),'0'))
ELSE 'False'
END)
=
(CASE WHEN TO_NUMBER(NVL(TRIM(p_StartPos),'0')) > 0 THEN NVL(UPPER(TRIM(p_StartPosValue)),'')
ELSE 'False'
END)
ORDER BY T1.ITEM
, T1.revision desc
;
END RPT_LIKE_PARTS_TEST;
/
You have to use UNION and not decode. In one side of UNION you have to handle parameter Y with outer join and other will be as you have coded already.
OR you need to use if / else of PLSQL since user can pass only one of them as parameter.
To be honest, this question is nothing specific to oracle and mere SQL.
so with the union all or union solution probably looks something like this
/* Formatted on 7/5/2016 1:50:34 PM (QP5 v5.256.13226.35510) */
SELECT T1.ITEM,
T1.REVISION,
T1.DESCRIPTION,
T2.CCN,
T2.DELETED,
T2.OBSOLETED,
T2.FINGOOD,
T2.ABC,
T3.MAS_LOC,
T3.LOCATION,
(T3.OH_QTY - T3.COM_QTY) - T3.RESV_QTY AS Avail_QTY,
T1.USER_NUM1,
CASE WHEN T2.HALT <> ' ' THEN 'Y' ELSE NULL END AS Halt,
T4.DESCRIPTION AS T4_Description,
det.OH_QTY AS Det_OH_QTY,
det.COM_QTY AS Det_COM_QTY,
DECODE (det.INSP_STAT, '3', 'Passed Inpection', DECODE det.INSP_STAT,'1','Waiting Inspection' ,' ')) as Inspect_Descr
, T3.RESV_QTY
from ITEM T1
LEFT OUTER JOIN ITEM_CCN T2
ON T1.ITEM=T2.ITEM
and T1.REVISION=T2.REVISION
LEFT OUTER JOIN ITEM_LOC T3
on T2.CCN=T3.CCN
and T2.ITEM=T3.ITEM
and T2.REVISION=T3.REVISION
LEFT OUTER JOIN HALT T4
on T2.HALT=T4.HALT
and T2.CCN=T4.CCN
LEFT OUTER JOIN ITEM_DET det
on T3.CCN=det.CCN
and T3.ITEM=det.ITEM
and T3.REVISION=det.REVISION
and T3.MAS_LOC=det.MAS_LOC
and T3.LOCATION=det.LOCATION
where T2.OBSOLETED is null and p_ViewAll = 'Y'
UNION ALL
SELECT T1.ITEM
, T1.REVISION
, T1.DESCRIPTION
, T2.CCN
, T2.DELETED
, T2.OBSOLETED
, T2.FINGOOD
, T2.ABC
, T3.MAS_LOC
, T3.LOCATION
, (T3.OH_QTY - T3.COM_QTY) - T3.RESV_QTY as Avail_QTY
, T1.USER_NUM1
, case when T2.HALT<>' ' then 'Y' else NULL end as Halt
, T4.DESCRIPTION as T4_Description
, det.OH_QTY as Det_OH_QTY
, det.COM_QTY as Det_COM_QTY
, DECODE(det.INSP_STAT,'3','Passed Inpection' ,DECODE det.INSP_STAT,'1','Waiting Inspection' ,' ')) as Inspect_Descr
, T3.RESV_QTY
from ITEM T1
LEFT OUTER JOIN ITEM_CCN T2
ON T1.ITEM=T2.ITEM
and T1.REVISION=T2.REVISION
LEFT OUTER JOIN ITEM_LOC T3
on T2.CCN=T3.CCN
and T2.ITEM=T3.ITEM
and T2.REVISION=T3.REVISION
LEFT OUTER JOIN HALT T4
on T2.HALT=T4.HALT
and T2.CCN=T4.CCN
LEFT OUTER JOIN ITEM_DET det
on T3.CCN=det.CCN
and T3.ITEM=det.ITEM
and T3.REVISION=det.REVISION
and T3.MAS_LOC=det.MAS_LOC
and T3.LOCATION=det.LOCATION
where T2.OBSOLETED is null and p_ViewAll = 'N'
and myfilterstuff = 'whatever'

The query performance is very low + correlated subquery

The query's aim is to get reserved rooms status is 3 or going to reserve in 30 to 45 minutes status in 2 or unreserved status in 1. reservation rooms are in RESEENH table and each reservation is in ORD_NOARCHIVE table which has begintime and endtime of reservation. So for each reservation room this query checks whether reservation is available at current time also its checks the meeting room parents and children. if children is reserved then parents are are blocked.
it takes 10 secs to fetch first 50 records.
with cte as
(
SELECT DISTINCT R.syscode,
R.behcode,
R.syscode AS FK_RESERVATIONUNIT, (
CASE
WHEN R.TYPE = 3 THEN '1'
WHEN R.TYPE = 1 THEN '2'
ELSE NULL
END ) AS LOCATION_TYPE,
R.sysobjalg AS FK_PROPERTY,
MP.syscode AS FK_MEASUREMENTPOINT,
MP.fk_plc_occupancy_state AS FK_PLC_OCCUPANCY_STATE,
F.syscode AS FK_FLOOR,
R.transitiontime,
r.type,
r.is_compoundreservationunit,
r.is_archived,
MP.fk_person,
os.transitionperiod
FROM reseenh R
--left outer join ordtrantbl RSS
--ON RSS.reservationunisyscode = R.syscode
left outer join objond F
ON F.syscode = R.fk_floor
left outer join pln_measurementpoint MP
ON MP.fk_reservationunit = R.syscode
AND MP.is_primary_measurement_point = 'T',
pln_ordersetting os
)
select cte.syscode,cte.behcode,cte.FK_RESERVATIONUNIT,
(CASE
WHEN O.begindatetime_user IS NULL THEN '1' --GREEN
WHEN O.begindatetime_user - (Nvl(cte.transitiontime, ( cte.transitionperiod ))/1440 ) > current_date THEN '2' -- ORANGE
WHEN O.begindatetime_user + (Nvl(cte.transitiontime, ( cte.transitionperiod )) /1440 ) > current_date THEN '3' -- RED
ELSE '3'
END ) AS LOCAVAILABILITY_STATUS_CODE,
cte.LOCATION_TYPE,
cte.FK_PROPERTY,
Coalesce(O.sysmelder, cte.fk_person) AS FK_PERSON,
O.syscode AS FK_ORDER,
O.ref_bostate_userdefined AS FK_ORDER_STATE_USER,
O.fk_bostate AS FK_ORDER_STATE_SYSTEM,
FK_MEASUREMENTPOINT,FK_PLC_OCCUPANCY_STATE,FK_FLOOR
from cte left outer join ord_noarchive O on O.syscode in
( SELECT MAX(ord.syscode) KEEP (DENSE_RANK FIRST ORDER BY ord.begindatetime_user) OVER (PARTITION BY ord.sysreseenh )
FROM ord_noarchive ORD
WHERE ( ( (
current_date >= ( ORD.begindatetime_user - ( Nvl(cte.transitiontime, ( cte.transitionperiod ))/1440) )
AND (
current_date - ( Nvl(cte.transitiontime, (cte.transitionperiod )) / 1440 ) ) <=ORD.enddatetime_user )
OR ( (
current_date + ( (
CASE
WHEN (
cte.TYPE = 1 ) THEN 30
ELSE 45
END ) / 1440 ) ) >= ( ORD.begindatetime_user - (Nvl(cte.transitiontime, ( cte.transitionperiod))/1440 ) )
AND (
current_date - ( Nvl(cte.transitiontime, ( cte.transitionperiod )) / 1440 ) ) < ORD.enddatetime_user ) )
AND ORD.sysreseenh IN
(
SELECT fk_reservationunit_parent
FROM pln_reservationunit_rut
WHERE fk_reservationunit_child IN
(
SELECT fk_reservationunit_child
FROM pln_reservationunit_rut
WHERE cte.is_compoundreservationunit = 'T'
AND fk_reservationunit_parent = cte.syscode)
UNION
SELECT cte.syscode
FROM dual
UNION
SELECT
CASE
WHEN cte.is_compoundreservationunit = 'T' THEN fk_reservationunit_child
ELSE fk_reservationunit_parent
END
FROM pln_reservationunit_rut
WHERE (
cte.is_compoundreservationunit = 'T'
AND fk_reservationunit_parent = cte.syscode )
OR (
cte.is_compoundreservationunit = 'F'
AND fk_reservationunit_child = cte.syscode ))
AND ORD.fk_bostate IN
(
SELECT syscode
FROM pln_bostate
WHERE pnname IN ( 'Requested',
'Made',
'AdministrativelyCompleted' )
AND fk_bodefinition = ref_bodefinition)
AND ORD.sysreseenh = O.sysreseenh
))
WHERE cte.is_archived = 'F'
AND cte.TYPE IN ( 1,
3 )
AND cte.fk_floor=495
No time to analyze the details of a very complex query, but my overall sense is that you are trying to do too many things at once. Separate the tasks. Check on room availability in one query, and check on the children/parent thing in a separate query.
Also, you could analyze the execution plan for the query and see what it bogging it down. My suspicion (again without time to really try to understand your query) is that at some point the mixing of tasks is translating into a many-to-many relationship where you have an intermediate result that is a cross product of rows between some of the tables in your query.

Wordpress mysql query not returning subcategory

I'm creating a custom query for another application to retrieve category and subcategory from the wordpress database. The wordpress data i'm attempting to retrieve is woocommerce products.
SELECT wp_posts.ID as product_code, v1.meta_value as sku, v2.meta_value as price, v3.meta_value as product_attributes, wp_posts.post_title as product_name, terms_1.name as category_name, terms_2.name as sub_category_name, wp_posts.post_excerpt as description FROM wp_posts
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN wp_term_taxonomy terms_tax_1 ON (wp_term_relationships.term_taxonomy_id = terms_tax_1.term_taxonomy_id)
LEFT JOIN wp_term_taxonomy terms_tax_2 ON (wp_term_relationships.term_taxonomy_id = terms_tax_2.term_taxonomy_id)
INNER JOIN wp_terms terms_1 ON (terms_tax_1.term_id = terms_1.term_id)
LEFT JOIN wp_terms terms_2 ON (terms_tax_2.term_id = terms_2.term_id)
INNER JOIN wp_postmeta v1 ON (wp_posts.ID = v1.post_id AND v1.meta_key = '_sku')
INNER JOIN wp_postmeta v2 ON (wp_posts.ID = v2.post_id AND v2.meta_key = '_price')
INNER JOIN wp_postmeta v3 ON (wp_posts.ID = v3.post_id AND v3.meta_key = '_product_attributes')
WHERE wp_posts.post_status = 'publish' AND wp_posts.post_type = 'product' AND
(terms_tax_1.taxonomy = 'product_cat' AND terms_tax_1.term_id='1646') OR (terms_tax_2.taxonomy = 'product_cat' AND terms_tax_2.parent='1646')
Everything is working but the category_name and sub_category_name returned are identical?
This is an example of an array returned, the sub_category_name should be Timber Framing
Array([product_code] => 12198
[sku] => 12198
[price] => 1.30
[product_attributes] => a:1:{s:12:"size-options";a:6:{s:4:"name";s:12:"Size Options";s:5:"value";s:82:"50mm x 50mm Green Treated | 50mm x 75mm Green Treated | 50mm x 100mm Green Treated";s:8:"position";s:2:"24";s:10:"is_visible";i:1;s:12:"is_variation";i:1;s:11:"is_taxonomy";i:0;}}
[product_name] => Budget Framing Timber
[category_name] => Timber for Garden
[sub_category_name] => Timber for Garden
[description] => This budget Framing Timber completes all the essentials for creating an economical decking area in your garden. It has been specially produced and treated so it can withstand heavy use. Its natural construction will give your new decking area a natural look whilst blending well with the surroundings in your garden. Guaranteed our timber is 100% FSC certified and fully tanalised to 15KG/M3.
)
Why are sub_category and category identical?
At quick glance it looks like you could probably use an extra set of parentheses around your OR block. Right now you've got:
WHERE
wp_posts.post_status = 'publish'
AND
wp_posts.post_type = 'product'
AND
(terms_tax_1.taxonomy = 'product_cat' AND terms_tax_1.term_id='1646')
OR
(terms_tax_2.taxonomy = 'product_cat' AND terms_tax_2.parent='1646')
And you probably want:
WHERE
wp_posts.post_status = 'publish'
AND
wp_posts.post_type = 'product'
AND
(
(terms_tax_1.taxonomy = 'product_cat' AND terms_tax_1.term_id='1646')
OR
(terms_tax_2.taxonomy = 'product_cat' AND terms_tax_2.parent='1646')
)
EDIT
On second thought, your query might be better using subqueries instead of joins. This query asks for all products and then optionally looks for categories and sub categories associated with it
SELECT
wp_posts.ID as product_code,
v1.meta_value as sku,
v2.meta_value as price,
v3.meta_value as product_attributes,
wp_posts.post_title as product_name,
( SELECT wp_terms.name FROM wp_term_taxonomy LEFT JOIN wp_term_relationships ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id LEFT JOIN wp_terms ON wp_term_taxonomy.term_id = wp_terms.term_id WHERE wp_term_taxonomy.term_id = 1646 ) as category_name,
( SELECT wp_terms.name FROM wp_term_taxonomy LEFT JOIN wp_term_relationships ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id LEFT JOIN wp_terms ON wp_term_taxonomy.term_id = wp_terms.term_id WHERE wp_term_taxonomy.parent = 1646 ) as sub_category_name,
wp_posts.post_excerpt as description
FROM
wp_posts
INNER JOIN
wp_postmeta v1 ON (wp_posts.ID = v1.post_id AND v1.meta_key = '_sku')
INNER JOIN
wp_postmeta v2 ON (wp_posts.ID = v2.post_id AND v2.meta_key = '_price')
INNER JOIN
wp_postmeta v3 ON (wp_posts.ID = v3.post_id AND v3.meta_key = '_product_attributes')
WHERE
wp_posts.post_status = 'publish'
AND
wp_posts.post_type = 'product'

getting total number to specific patients in rdlc report

I have made an rdlc report of total number of patients in a day and it works fine. I have the total number of female male patients, but when the report binds it returns a total equal to the number of rows in my data.
For example if I have 20 rows in my report then below when I print the count it returns the count in 20 rows.
How can I get it to be in only 1 row?
This is the query I'm using:
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON GO
ALTER PROCEDURE [dbo].[Test_test_test]-- '2013/08/02'
-- Add the parameters for the stored procedure here
-- Add the parameters for the stored procedure here
(#date VARCHAR(20))
AS
BEGIN
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SELECT ( CASE
WHEN OLD_NEW_PATIENT.OLD_NEW = 'new' THEN
PATIENT_REF_MASTER.PAT_ID
ELSE NULL
END ) AS 'new',
( CASE
WHEN OLD_NEW_PATIENT.OLD_NEW = 'old' THEN
PATIENT_REF_MASTER.PAT_ID
ELSE NULL
END ) AS 'old',
----------------------------------------
( CASE
WHEN GENDER_MASTER.NAME1 = 'Female' THEN GENDER_MASTER.NAME1
ELSE NULL
END ) AS
'Females',
( CASE
WHEN GENDER_MASTER.NAME1 = 'Male' THEN GENDER_MASTER.NAME1
ELSE NULL
END ) AS 'Males',
-------------------------------------
CONVERT(VARCHAR, PATIENT_REF_MASTER.CREATION_DATE, 105) AS
'creation_Date',
PATIENT_REF_MASTER.SR_NO AS 'sr_No',
PATIENT_MASTER.PAT_FNAME + ' '
+ PATIENT_MASTER.PAT_SNAME AS 'NAME',
DEPT_ID AS
'Dept_ID',
DEPT_MASTER.DEPT_NAME AS
'Dept_Name',
DOC_MASTER.DOC_ID AS
'Doc_Master',
DOC_MASTER.DOC_FNAME + ' '
+ DOC_MASTER.DOC_SNAME AS
'Doc_Name'
,
PATIENT_MASTER.PAT_ADDR
AS 'addr',
GENDER_MASTER.NAME1 AS
'Pat_Sex',
PATIENT_MASTER.AGE AS 'age',
(SELECT Count(PATIENT_REF_MASTER.SR_NO)
FROM PATIENT_REF_MASTER
WHERE PATIENT_REF_MASTER.CREATION_DATE = #date) AS 'count',
(SELECT Count(PATIENT_MASTER.PAT_SEX)
FROM PATIENT_MASTER
LEFT JOIN PATIENT_REF_MASTER
ON PATIENT_REF_MASTER.PAT_ID =
PATIENT_MASTER.PAT_CODE
WHERE PATIENT_REF_MASTER.CREATION_DATE = #date
AND PATIENT_MASTER.PAT_SEX = 2) AS
'F_count',
(SELECT Count(PATIENT_MASTER.PAT_SEX)
FROM PATIENT_MASTER
LEFT JOIN PATIENT_REF_MASTER
ON PATIENT_REF_MASTER.PAT_ID =
PATIENT_MASTER.PAT_CODE
WHERE PATIENT_REF_MASTER.CREATION_DATE = #date
AND PATIENT_MASTER.PAT_SEX = 1) AS
'M_count'
FROM PATIENT_REF_MASTER
LEFT JOIN DBO.OLD_NEW_PATIENT
ON DBO.OLD_NEW_PATIENT.CODE = PATIENT_REF_MASTER.OLD_NEW
LEFT JOIN DBO.DEPT_MASTER
ON DEPT_MASTER.DEPT_CODE = PATIENT_REF_MASTER.DEPT_ID
LEFT JOIN PATIENT_MASTER
ON PATIENT_MASTER.PAT_CODE = PATIENT_REF_MASTER.PAT_ID
LEFT JOIN DOC_MASTER
ON DOC_MASTER.DOC_ID = PATIENT_REF_MASTER.DOC_ID
LEFT JOIN GENDER_MASTER
ON GENDER_MASTER.CODE = PATIENT_MASTER.PAT_SEX
WHERE PATIENT_REF_MASTER.CREATION_DATE = #date
--MONTH(Patient_Ref_master.creation_Date)=#month and Dept_ID=#dept
ORDER BY PATIENT_REF_MASTER.SR_NO ASC
-- select Dept_Master.Dept_Name as 'Dept_Name',
-- count(Pat_ID) as 'Pat_ID'
--
-- from Patient_Ref_master
--left join dbo.Dept_Master on Dept_Master.Dept_code = Patient_Ref_master.Dept_ID
--where MONTH(Patient_Ref_master.creation_Date)=#month and Dept_ID=#dept
--group by Dept_Master.Dept_Name
END
I think you're trying to do to many things at once ;-)
The heart of your problem lies here:
SELECT Count(PATIENT_MASTER.PAT_SEX)
FROM PATIENT_MASTER
LEFT JOIN PATIENT_REF_MASTER
ON PATIENT_REF_MASTER.PAT_ID =
PATIENT_MASTER.PAT_CODE
WHERE PATIENT_REF_MASTER.CREATION_DATE = #date
AND PATIENT_MASTER.PAT_SEX = 1
By using this query within your query, it will return the total in each and every row. This is also why you can get away with writing the query and not using the GROUP BY clause.
I suggest you do all the work in this query with the exception of the count, and then use another query outside of this one for the count.
A secondary problem is that in your query you're requesting several details about each row, but you want it to come back in one row. You have to decide what you want ;).
In order to get just the counts in one row, try something like this:
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON GO
ALTER PROCEDURE [dbo].[Test_test_test]-- '2013/08/02'
-- Add the parameters for the stored procedure here
-- Add the parameters for the stored procedure here
(#date VARCHAR(20))
AS
BEGIN
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SELECT Count(*) count,
Sum(CASE
WHEN FEMALES IS NOT NULL THEN 1
ELSE 0
END) F_Count,
Sum(CASE
WHEN MALES IS NOT NULL THEN 1
ELSE 0
END) M_Count
FROM (SELECT ( CASE
WHEN OLD_NEW_PATIENT.OLD_NEW = 'new' THEN
PATIENT_REF_MASTER.PAT_ID
ELSE NULL
END ) AS
'new',
( CASE
WHEN OLD_NEW_PATIENT.OLD_NEW = 'old' THEN
PATIENT_REF_MASTER.PAT_ID
ELSE NULL
END ) AS
'old',
----------------------------------------
( CASE
WHEN GENDER_MASTER.NAME1 = 'Female' THEN
GENDER_MASTER.NAME1
ELSE NULL
END ) AS
'Females',
( CASE
WHEN GENDER_MASTER.NAME1 = 'Male' THEN
GENDER_MASTER.NAME1
ELSE NULL
END ) AS
'Males',
-------------------------------------
CONVERT(VARCHAR, PATIENT_REF_MASTER.CREATION_DATE, 105) AS
'creation_Date',
PATIENT_REF_MASTER.SR_NO AS
'sr_No',
PATIENT_MASTER.PAT_FNAME + ' '
+ PATIENT_MASTER.PAT_SNAME AS
'NAME'
,
DEPT_ID
AS 'Dept_ID',
DEPT_MASTER.DEPT_NAME AS
'Dept_Name',
DOC_MASTER.DOC_ID AS
'Doc_Master',
DOC_MASTER.DOC_FNAME + ' '
+ DOC_MASTER.DOC_SNAME AS
'Doc_Name',
PATIENT_MASTER.PAT_ADDR AS
'addr'
,
GENDER_MASTER.NAME1
AS 'Pat_Sex',
PATIENT_MASTER.AGE AS
'age'
FROM PATIENT_REF_MASTER
LEFT JOIN DBO.OLD_NEW_PATIENT
ON DBO.OLD_NEW_PATIENT.CODE =
PATIENT_REF_MASTER.OLD_NEW
LEFT JOIN DBO.DEPT_MASTER
ON DEPT_MASTER.DEPT_CODE =
PATIENT_REF_MASTER.DEPT_ID
LEFT JOIN PATIENT_MASTER
ON PATIENT_MASTER.PAT_CODE =
PATIENT_REF_MASTER.PAT_ID
LEFT JOIN DOC_MASTER
ON DOC_MASTER.DOC_ID = PATIENT_REF_MASTER.DOC_ID
LEFT JOIN GENDER_MASTER
ON GENDER_MASTER.CODE = PATIENT_MASTER.PAT_SEX
WHERE PATIENT_REF_MASTER.CREATION_DATE = #date
--MONTH(Patient_Ref_master.creation_Date)=#month and Dept_ID=#dept
)T
ORDER BY PATIENT_REF_MASTER.SR_NO ASC
END
I hope this helps, let me know if you need any more info.
Edit
Found a small mistake in the query I posted, the field names should have been FEMALES not FEMALE and MALES not MALE.
I also set up a scaled down example in SQL Fiddle. Take a look and tell me what you think.

dbo.StoredProcedure SQL Syntax error near 'SELECT' and near 'AS'

Hey guys I hope you can help me I've tried every thing I can think of and it keeps telling me that my syntax near SELECT and that my syntax near AS is incorrect
CREATE PROCEDURE dbo.StoredProcedure2
SELECT
, Announcements.ID
, Announcement.CreateDate
, Announcements.Announcement
,aspnet_Users.UserName
,(SELECT Announcement_Read_State.Read_Date
FROM Announcement_Read_State
WHERE Announcement_Read_State.Announcement_ID = Announcements.ID
AND Announcement_Read_State.User_ID = 2) AS ReadState
FROM Announcements INNER JOIN aspnet_User ON Announcements .Sender_User_ID = aspnet_User.UserName
WHERE (Announcements.ID IN
( SELECT Max(Announcements.ID)
FROM Thread_Participant INNER JOIN Announcements ON
Thread_Participant.ThreadId = Announcements.Announcement_ThreadId
WHERE MessageThreadParticipant.UserID = 2
GROUP BY ThreadParticipant.AnnouncementThreadId
)
ORDER BY Message.CreateDate DESC;
It should be:
CREATE PROCEDURE dbo.StoredProcedure2
AS -- you were missing this
SELECT -- you had an extra comma here
Announcements.ID
, Announcement.CreateDate
, Announcements.Announcement
,aspnet_Users.UserName
,(SELECT Announcement_Read_State.Read_Date
FROM Announcement_Read_State
WHERE Announcement_Read_State.Announcement_ID = Announcements.ID
AND Announcement_Read_State.User_ID = 2) AS ReadState
FROM Announcements INNER JOIN aspnet_User ON Announcements .Sender_User_ID = aspnet_User.UserName
WHERE (Announcements.ID IN
( SELECT Max(Announcements.ID)
FROM Thread_Participant INNER JOIN Announcements ON
Thread_Participant.ThreadId = Announcements.Announcement_ThreadId
WHERE MessageThreadParticipant.UserID = 2
GROUP BY ThreadParticipant.AnnouncementThreadId
)
)-- you were missing this one
ORDER BY Message.CreateDate DESC;

Resources