Note that there are some explanatory texts on larger screens.

plurals
  1. POCTE-common table exp in t-sql
    primarykey
    data
    text
    <p>I have a problem with the following query:</p> <pre><code>WITH CTE_1 (stu_id ,meet_doc_id ,doc_name ,stu_name ,dob ,done ,date_meet_doc) AS (SELECT stu_id ,meet_doc_id ,doc_name ,stu_name ,dob ,CASE WHEN (PATINDEX('%SMOKING%',act.VALUE)) THEN 'LMDO' WHEN (PATINDEX('%NOT SMOKING%',act.VALUE)) THEN 'LMD1' WHEN (ISNULL(CAST(act.VALUE as varchar(max)),'')='') THEN 'CLEAR' ELSE 'CLEAR' END done ,date_meet_doc FROM abc INNER JOIN INNER JOIN INNER JOIN WHERE multiple conditions ) SELECT * FROM CTE_1 one WHERE date =(SELECT MAX(DATE) FROM CTE_1 two WHERE two.stu_id=one.stu_id AND one.doc_name=two.doc_name) ORDER BY stu_name,dob ; </code></pre> <p>The result set of the inner query(CTE_1) for three student(for eg) will be something like</p> <pre><code>stu_id meet_doc_id doc_name stu_name dob value date 101 0104 AD AM 15/06/1950 LMDO 2011-02-15 101 0105 AD AM 15/06/1950 CLEAR 2011-02-18 101 0106 AD AM 15/06/1950 CLEAR 2011-02-25 102 0107 AD AK 12/08/1987 CLEAR 2011-03-28 102 0108 AD AK 12/08/1987 LDMO 2011-04-29 103 0109 PK LMP 13/07/1970 CLEAR 2011-03-28 103 0110 PK LMP 13/07/1970 CLEAR 2011-05-12 </code></pre> <p>AND when i execute the whole query my result set will be </p> <pre><code>stu_id meet_doc_id doc_name stu_name dob value date 101 0106 AD AM 15/06/1950 CLEAR 2011-02-25 102 0108 AD AK 12/19/1987 LDMO 2011-04-29 103 0110 PK LMP 13/07/1970 CLEAR 2011-05-12 </code></pre> <p><strong>What do i have to do to change the outer query to select only those value ie LDMO or LMD1 for a particular student and whose doctor is same?</strong> </p> <p>Suppose if the student meets the doc multiple times and if in any of the cases if the student gets a LMDO or LMD1 then it should pick only that record irrespective of the date. </p> <p>I am expecting my resultset to be something like:</p> <pre><code>stu_id meet_doc_id doc_name stu_name dob value date 101 0104 AD AM 15/06/1950 LMDO 2011-02-15 102 0107 AD AK 12/08/1987 CLEAR 2011-03-28 103 0110 PK LMP 13/07/1970 CLEAR 2011-05-12 </code></pre> <p>The logic behind it is if the stu_id is same and the doc_name is same and if there exists a value either LMDO or LMD1 then show that record if not show the record which has CLEAR. Simply i want to remove the MAX(date) and place a condition for the whole reporting period of that particular stu_id with the same doc_name.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload