Can't order query correctly - sql

A while ago I requested help to code a LEFT JOIN filtering in a particular way that the result postition the desired value in the first row.
Need to retrieve table's last inserted/updated record with some exclusions
The thing now is that there are many cases which are mixing data. The scenario is that on the same table we have 2 values that we need to organize on different columns. The PO_ID is unique, but can have 1 or more values on the other tables, and for this particular case 1 PO_ID has 3 SHIP_ID_CUS values. We only need 1 PO_ID per row (no duplicates) that is way we used the MAX() and GROUP BY.
Here is a piece of the code that I think cause issues.
select
z.po_id,
max(scdc.ship_id) as ship_id_cdc,
max(lscdc.ship_evnt_cd) as last_event_cdc,
max(lscdc.ship_evnt_tms) as event_tms_cdc,
max(scus.SHIP_ID) as ship_id_cus,
max(lscus.ship_evnt_cd) as last_event_cus,
max(lscus.ship_evnt_tms) as event_tms_cus
from TABLE.A z
left join (select distinct po_id, iltc.ship_id, s.ship_to_loc_code from TABLE.B iltc inner join TABLE.C s on iltc.ship_id=s.ship_id and iltc.ship_to_loc_code=s.ship_to_loc_code and s.ship_to_ctry<>' ') AS A ON z.po_id = a.po_id
left JOIN TABLE.C scus ON A.SHIP_ID = scus.SHIP_ID AND A.SHIP_TO_LOC_CODE = scus.SHIP_TO_LOC_CODE and scus.loc_type = 'CUS' AND DAYS(scus.shipment_tms)+10 >= DAYS(z.ship_tms)
left JOIN TABLE.C scdc ON A.SHIP_ID = scdc.SHIP_ID AND A.SHIP_TO_LOC_CODE = scdc.SHIP_TO_LOC_CODE and scdc.loc_type = 'CDC' AND DAYS(scdc.shipment_tms)+10 >= DAYS(z.ship_tms)
left join
( select ship_id_856, ship_to_loc_cd856, ship_evnt_cd, ship_evnt_tms, carr_tracking_num, event_srv_lvl
, row_number() over(partition by ship_id order by updt_job_tms desc) as RN
FROM TABLE.D
WHERE LEFT(ship_evnt_cd, 1) <> '9') lscus
ON lscus.ship_id_856=scus.ship_id and scus.ship_to_loc_code=lscus.ship_to_loc_cd856 and lscus.rn = 1
left join
( select ship_id_856, ship_to_loc_cd856, ship_evnt_cd, ship_evnt_tms, carr_tracking_num, event_srv_lvl
, row_number() over(partition by ship_id order by updt_job_tms desc) as RN
FROM TABLE.D
WHERE LEFT(ship_evnt_cd, 1) <> '9') lscdc
ON lscdc.ship_id_856=scdc.ship_id and lscdc.ship_to_loc_cd856=scdc.ship_to_loc_code and lscdc.rn = 1
WHERE
z.po_id = 'T1DLDC'
GROUP BY z.po_id
By searching that condition we get the following result
The problem is that if we search directly on the TABLE.D, the last event that we need (with last update record tms) is another one (X1) and somehow the date is incorrect.
What is even more weird, is that if we search for the ship_id_cus on the original query, we get the correct code but still with a wrong date...
WHERE
--z.po_id = 'T1DLDC'
scus.ship_id = 'D30980'
GROUP BY z.po_id
I tried other logic changes like modifying the left joins to search on a subquery.
left JOIN ( select * from TABLE.C order by updt_job_tms desc) scus ON A.SHIP_ID = scus.SHIP_ID AND A.SHIP_TO_LOC_CODE = scus.SHIP_TO_LOC_CODE and scus.loc_type = 'CUS' AND DAYS(scus.shipment_tms)+10 >= DAYS(z.ship_tms)
But this is also giving the same exact results by searching either by po_id or ship_id_cus
Any ideas or comment will be much appreciated.
Thanks
------------------------------------UPDATE-----------------------------------
Adding the result of the LEFT JOIN with the row_partition() including all the ship_id_cus for that po_id, and all the codes with the tms. None match here.
Based on all these, it should be the last ship_id_cus with X1 event/tms. If we exclude also the ones starting with 9, we would get the following result.
(I am not applying here ordering by ship_id_cus, which already described before that did not work either the way I implemented)

If you have a table: TBL1
ID APPROVED APPROVER DATE_APPROVED
====== ======== ======== =============
ABC Y JOE 2019-01-13
ABC N ZACK 2018-12-23
ABC N SUE 2019-02-23
And you do SQL:
SELECT ID, MAX(APPROVED) AS APPROVAL
,MAX(APPROVER) AS APPROVED_BY , MAX(DATE_APPROVED) AS APPROVED_ON
FROM TBL1 GROUP BY ID
you will get result:
ID APPROVAL APPROVED_BY APPROVED_ON
====== ======== =========== =============
ABC Y ZACK 2019-02-23
which is correct to the code but is NOT what you want
Try the following:
SELECT T1.ID, T1.APPROVED, T1.APPROVER, T1.DATE_APPROVED
FROM TBL1 AS T1
INNER JOIN (SELECT ID, MAX(DATE_APPROVED) AS APPROVED_ON
FROM TBL1 GROUP BY ID
) AS T2
ON T1.ID =T2.ID
AND T1.DATE_APPROVED = T2.APPROVED_ON
Result:
ID APPROVED APPROVER DATE_APPROVED
====== ======== ======== =============
ABC N SUE 2019-02-23

Related

Multiple joins chose latest record by date

I am trying to link four tables (3 of them key to this question). I need to pull the latest payment type used from T16. T16 links to T17 via headerid, which links to A10 via pledgeid.
I have tried this a bunch of different ways. The code below is giving me the latest date for each payment type, but what I really want is just the last payment type.
SELECT DISTINCT
A10.RecordId
,A10.AccountNumber
,A01.FamilyId
,a01.FamilyMemberType
,A10.PledgeCode --Child Number
,A10.OriginalPledgeId
,A10.PledgeId
,A01.FirstName
,A01.LastName
,A10.PledgeStatus
,A10.AmountPerGift
,A10.PledgeFrequency
,t16.PaymentType
FROM
A10_AccountPledges A10
LEFT JOIN
A01_AccountMaster A01 ON a01.AccountNumber = a10.AccountNumber
LEFT JOIN
T17_RecurringDonations T17 ON T17.PledgeId = A10.PledgeId
LEFT JOIN
T16_RecurringTransactionHeaders T16 ON T16.HeaderId = T17.HeaderId
INNER JOIN
(SELECT
T17.pledgeID
,MAX(T16.LastUsedDate) as lastdate
FROM
T17_RecurringDonations T17
LEFT JOIN
T16_RecurringTransactionHeaders T16 ON T16.HeaderId = T17.HeaderId
GROUP BY
T17.pledgeID) pm ON pm.PledgeId = A10.PledgeId --and pm.lastdate = T16.LastUsedDate
WHERE
A01.[Status] = 'A'
AND a10.PledgeId = 398353 --test case
You can do this like below:
select top 1 *
from (
YOUR QUERY HERE
)
order by lastdate desc;
Notes:
YOUR QUERY HERE is a placeholder which will hold your whole query as a subquery
you need to add the selection of lastdate to your subselect in order to make sure you can order by lastdate desc
EDIT
As #spaindc explained, this idea was applied, resulting in
SELECT distinct
A10.AccountNumber
,A01.FamilyId
,a01.FamilyMemberType
,A10.PledgeCode --Child Number
,A10.OriginalPledgeId
,A10.PledgeId
,A01.FirstName
,A01.LastName
,A10.PledgeStatus
,A10.PledgeFrequency
,(SELECT top 1 T16.PaymentType
FROM T16_RecurringTransactionHeaders T16, T17_RecurringDonations T17
where T16.HeaderId = T17.HeaderId
and T17.PledgeId = A10.PledgeId
order by t16.LastUsedDate desc
) as PaymentType
FROM A10_AccountPledges A10
left join A01_AccountMaster A01 on a01.AccountNumber = a10.AccountNumber
where A01.[Status] = 'A'
Thanks to Lajos for correct answer. Here is the final code for reference.
SELECT distinct
A10.AccountNumber
,A01.FamilyId
,a01.FamilyMemberType
,A10.PledgeCode --Child Number
,A10.OriginalPledgeId
,A10.PledgeId
,A01.FirstName
,A01.LastName
,A10.PledgeStatus
,A10.PledgeFrequency
,(SELECT top 1 T16.PaymentType
FROM T16_RecurringTransactionHeaders T16, T17_RecurringDonations T17
where T16.HeaderId = T17.HeaderId
and T17.PledgeId = A10.PledgeId
order by t16.LastUsedDate desc
) as PaymentType
FROM A10_AccountPledges A10
left join A01_AccountMaster A01 on a01.AccountNumber = a10.AccountNumber
where A01.[Status] = 'A'

Better way of writing a nested query in SQl

I wrote a piece of code and I was wondering if there is a more elegant, more efficient way of writing it.
SELECT act1.ACTIVITY_DETAIL_ID FROM CPMS.ACTIVITY_TRANSACTION act1
WHERE act1.USER_CREATED ='CPMSAutoRecovery'
AND act1.TRANSACTION_GROUP_ID =23 --commitment, not entitled
GROUP BY act1.ACTIVITY_DETAIL_ID HAVING COUNT(*)>1
AND act1.ACTIVITY_DETAIL_ID IN (
select ad.ACTIVITY_DETAIL_ID from CPMS.activity_detail ad, CPMS.PARTY_ROLE pr
where pr.ACTIVITY_REGISTRY_ID = ad.activity_registry_id
AND pr.PARTY_ROLE_type_ID=2
AND pr.PARTY_ID IN (
select distinct i.PARTY_ID FROM CPMS.INDIVIDUAL i, CPMS.PARTY_ROLE pr where
I.PARTY_ID = PR.PARTY_ID AND i.EXPIRY_DATE is null
)
)
order by act1.ACTIVITY_DETAIL_ID;
this is the key dependencies of the tables:
INDIVIDUAL
----------
PARTY_ID
PARTY_ROLE
------------
ACTIVITY_REGISTRY_ID
PARTY_ID
ACTIVITY_DETAIL
-----------------
ACTIVITY_DETAIL_ID
ACTIVITY_REGISTRY_ID
ACTIVITY_TRANSACTION
----------------------
ACTIVITY_TRANSACTION_ID
ACTIVITY_DETAIL_ID
UPDATE:
I made it a JOIN
SELECT act1.ACTIVITY_DETAIL_ID FROM CPMS.ACTIVITY_TRANSACTION act1
JOIN CPMS.ACTIVITY_DETAIL ad ON act1.ACTIVITY_DETAIL_ID = ad.ACTIVITY_DETAIL_ID
JOIN CPMS.PARTY_ROLE pr ON ad.ACTIVITY_REGISTRY_ID = pr.ACTIVITY_REGISTRY_ID
JOIN CPMS.INDIVIDUAL i ON pr.PARTY_ID = i.PARTY_ID
WHERE act1.USER_CREATED ='CPMSAutoRecovery'
AND act1.TRANSACTION_GROUP_ID =23
AND pr.PARTY_ROLE_type_ID=2
AND i.EXPIRY_DATE is null
GROUP BY act1.ACTIVITY_DETAIL_ID HAVING COUNT(*)>1
order by act1.ACTIVITY_DETAIL_ID;

Combining two tables including rows not found in other table, substituting values in column

I have two tables made from the following two queries:
SELECT t3.PatientID, SUM(t3.Fee) as total FROM
(SELECT t1.TestID, t2.PatientID, t1.Fee FROM
(SELECT Test.TestID, Test.Fee FROM MedicalTest AS Test) AS t1,
(SELECT T.TestID, T.PatientID FROM Take AS T) AS t2
WHERE t1.TestID = t2.TestID
ORDER BY t2.PatientID) AS t3
GROUP BY t3.PatientID
ORDER BY total DESC;
Which gives me a table of patient IDs and how much they have spent on tests, a portion of the table looks like this:
PATIENTID TOTAL
----------- ---------------------------------
99642131 550.00
99631255 440.00
99665378 430.00
99627956 310.00
99657423 280.00
99641125 260.00
99630025 230.00
99648682 230.00
My other query:
SELECT DISTINCT D.PatientID FROM Diagnose AS D
WHERE D.PhysicianID IN (
SELECT P.PhysicianID FROM Physician AS P
WHERE P.HName = 'Specific Hospital'
AND P.DName = 'Intensive Care Unit');
Returns to me a list of Patient IDs who are under the care of a specific physician. A portion of the table:
PATIENTID
-----------
99615376
99618797
99620783
99620882
99621221
I am trying to create a resultant table that contains the patient IDs from the second table as well as how much they have spent on medical tests from the first table. Some patients from the second table have not taken any tests in which case, I would like the table to simply give 0 for the total column, however, my attempt at combining the tables only gives me the patients who have taken tests:
SELECT t5.PatientID, t4.total FROM
(SELECT t3.PatientID, SUM(t3.Fee) as total FROM
(SELECT t1.TestID, t2.PatientID, t1.Fee FROM
(SELECT Test.TestID, Test.Fee FROM MedicalTest AS Test) AS t1,
(SELECT T.TestID, T.PatientID FROM Take AS T) AS t2
WHERE t1.TestID = t2.TestID
ORDER BY t2.PatientID) AS t3
GROUP BY t3.PatientID
ORDER BY total DESC) AS t4,
(SELECT DISTINCT D.PatientID FROM Diagnose AS D
WHERE D.PhysicianID IN (
SELECT P.PhysicianID FROM Physician AS P
WHERE P.HName = 'Specific Hospital'
AND P.DName = 'Intensive Care Unit')) AS t5
WHERE t5.PatientID = t4.PatientID;
Resultant table:
PATIENTID TOTAL
----------- ---------------------------------
99642131 550.00
99665378 430.00
99627956 310.00
How can I include the patients from table 2 that have not taken tests and enter 0 in their total column?
I managed to write the following query:
SELECT DISTINCT D.PatientID, COALESCE(total, '0') AS finalTotal
FROM Diagnose AS D
LEFT JOIN (
SELECT T.PatientID, SUM(M.Fee) AS total
FROM Take AS T, MedicalTest AS M
WHERE T.TestID = M.TestID
GROUP BY T.PatientID
) AS t1
ON t1.PatientID = D.PatientID
WHERE D.PhysicianID IN (
SELECT P.PhysicianID FROM Physician AS P
WHERE P.HName = 'Specific Hospital'
AND P.DName = 'Intensive Care Unit')
ORDER BY finalTotal DESC;
I use COALESCE(total, '0') with my LEFT JOIN to input 0 on the rows where no medical tests were done. This lead me to my desired output:
PATIENTID FINALTOTAL
----------- ------------------------------------------
99642131 550.00
99665378 430.00
99627956 310.00
99615376 0
99618797 0
99620783 0
99620882 0
99621221 0
99642157 0
99655482 0
99664061 0

Select Latest or most recent date in SQL query

I am running a query in SQL on our EHR/EMR database. I am primarily looking at an assessment that is done by a nurse during each patient encounter/visit and looking to return an answer for the most recent assessment date along with some other info. I have the query created and all the data is coming over, however, it is returning all assessment dates and the answers instead of just the latest date and answer. I'll attach the full code below.
SELECT DISTINCT
MAX(PTA.ASSESSMENT_DATE) AS Max_Date,
SAQ.QUESTION_TEXT, SAA.ANSWER_TEXT, dbo.PT_BASIC.PATIENT_CODE,
dbo.PT_BASIC.NAME_FULL
FROM
dbo.PTC_ASSESSMENT_ANSWER AS PAA
INNER JOIN
dbo.PTC_ASSESSMENT AS PTA ON PTA.ASSESSMENT_ID = PAA.ASSESSMENT_ID
AND PTA.PATIENT_ID = PAA.PATIENT_ID
INNER JOIN
dbo.SYS_ASSESSMENT_POINTER AS SAP ON SAP.POINTER_ID = PAA.POINTER_ID
INNER JOIN
dbo.SYS_ASSESSMENT_QUESTION AS SAQ ON SAQ.QUESTION_ID = SAP.QUESTION_ID
INNER JOIN
dbo.SYS_ASSESSMENT_ANSWER AS SAA ON SAA.ANSWER_ID = SAP.ANSWER_ID
INNER JOIN
dbo.PT_BASIC ON PTA.PATIENT_ID = dbo.PT_BASIC.PATIENT_ID
WHERE
(PTA.ASSESSMENT_DATE BETWEEN CONVERT(DATETIME, '2017-09-05 00:00:00', 102)
AND CONVERT(DATETIME, '2017-10-12 00:00:00', 102))
GROUP BY
dbo.PT_BASIC.PATIENT_CODE, dbo.PT_BASIC.NAME_FULL, SAQ.QUESTION_TEXT,
SAA.ANSWER_TEXT
HAVING
(SAA.ANSWER_TEXT LIKE '%LEVEL % -%')
The current output would be something similar to this:
9/5/2017 PATIENT ABC Answer1
9/6/2017 PATIENT ABC Answer2
9/7/2017 PATIENT ABC Answer3
9/6/2017 PATIENT XYZ Answer4
What I am expecting is:
9/7/2017 PATIENT ABC Answer3
9/6/2017 PATIENT XYZ Answer4
If your version of SQL Server supports it, using ROW_NUMBER() OVER() is an efficient and simple method for arriving at "latest" (or "earliest") rows from a single table. However as we know so little about your data model it isn't easy to guess how to reduce the rows to just the "lastest answer" which probably requires a more complex subquery. However you can still use ROW_NUMBER() OVER() on that subquery. I suspect that the nature of questions and answers is that the table aliases SAP, SAQ, SAA may all need to be involved in this subquery.
Note that instead of directly joining PTA this is now a subquery and the join condition to the outer query requires that RN=1 which is the row with the "latest" date.
SELECT
MAX(PTA.ASSESSMENT_DATE) AS Max_Date
, SAQ.QUESTION_TEXT
, SAA.ANSWER_TEXT
, dbo.PT_BASIC.PATIENT_CODE
, dbo.PT_BASIC.NAME_FULL
FROM dbo.PTC_ASSESSMENT_ANSWER AS PAA
INNER JOIN (
SELECT
*
, ROW_NUMBER() OVER (PARTITION BY PATIENT_ID
ORDER BY ASSESSMENT_DATE DESC) AS RN
FROM dbo.PTC_ASSESSMENT
WHERE ASSESSMENT_DATE BETWEEN '20170905' AND '20171012'
) AS PTA ON PTA.ASSESSMENT_ID = PAA.ASSESSMENT_ID
AND PTA.PATIENT_ID = PAA.PATIENT_ID
AND PTA.RN = 1
INNER JOIN dbo.SYS_ASSESSMENT_POINTER AS SAP ON SAP.POINTER_ID = PAA.POINTER_ID
INNER JOIN dbo.SYS_ASSESSMENT_QUESTION AS SAQ ON SAQ.QUESTION_ID = SAP.QUESTION_ID
INNER JOIN dbo.SYS_ASSESSMENT_ANSWER AS SAA ON SAA.ANSWER_ID = SAP.ANSWER_ID
INNER JOIN dbo.PT_BASIC ON PTA.PATIENT_ID = dbo.PT_BASIC.PATIENT_ID
WHERE SAA.ANSWER_TEXT LIKE '%LEVEL % -%'
GROUP BY
dbo.PT_BASIC.PATIENT_CODE
, dbo.PT_BASIC.NAME_FULL
, SAQ.QUESTION_TEXT
, SAA.ANSWER_TEXT
select distinct is not required on this query (or any similar query using GROUP BY)
yyymmdd is the safest date literal in SQL Server, you don't need the converts using style 102
your having clause should be moved to a where clause as it does not evaluate any aggregated value
Cross apply allows you to use a correlated query and chive the top most n records ordered by date desc for each patient assessment. (after review maybe you just need patient?)
Perhaps just change:
INNER JOIN
dbo.PTC_ASSESSMENT AS PTA ON PTA.ASSESSMENT_ID = PAA.ASSESSMENT_ID
AND PTA.PATIENT_ID = PAA.PATIENT_ID
TO:
CROSS APPLY (SELECT TOP 1 *
FROM dbo.PTC_ASSESSMENT PTA2
WHERE PTA2.ASSESSMENT_ID = PAA.ASSESSMENT_ID
/*AND PTA2.PATIENT_ID = PAA.PATIENT_ID*/
ORDER BY PTA2.Assessment_date desc) PTA
GIVING YOU: (I left the /AND PTA2.PATIENT_ID = PAA.PATIENT_ID/ --I think you can omit this. I left the */ in place but it's not needed)
SELECT MAX(PTA.ASSESSMENT_DATE) AS Max_Date
, SAQ.QUESTION_TEXT
, SAA.ANSWER_TEXT
, dbo.PT_BASIC.PATIENT_CODE
, dbo.PT_BASIC.NAME_FULL
FROM dbo.PTC_ASSESSMENT_ANSWER AS PAA
CROSS APPLY (SELECT TOP 1 *
FROM dbo.PTC_ASSESSMENT PTA2
WHERE PTA2.ASSESSMENT_ID = PAA.ASSESSMENT_ID --I think you can omit this.
/*AND PTA2.PATIENT_ID = PAA.PATIENT_ID*/
ORDER BY PTA2.Assessment_date desc) PTA
INNER JOIN dbo.SYS_ASSESSMENT_POINTER AS SAP
ON SAP.POINTER_ID = PAA.POINTER_ID
INNER JOIN dbo.SYS_ASSESSMENT_QUESTION AS SAQ
ON SAQ.QUESTION_ID = SAP.QUESTION_ID
INNER JOIN dbo.SYS_ASSESSMENT_ANSWER AS SAA
ON SAA.ANSWER_ID = SAP.ANSWER_ID
INNER JOIN dbo.PT_BASIC
ON PTA.PATIENT_ID = dbo.PT_BASIC.PATIENT_ID
WHERE (PTA.ASSESSMENT_DATE BETWEEN CONVERT(DATETIME, '2017-09-05 00:00:00', 102) AND CONVERT(DATETIME, '2017-10-12 00:00:00', 102))
GROUP BY dbo.PT_BASIC.PATIENT_CODE
, dbo.PT_BASIC.NAME_FULL
, SAQ.QUESTION_TEXT
, SAA.ANSWER_TEXT
HAVING (SAA.ANSWER_TEXT LIKE '%LEVEL % -%')
It appears you're not concerned about patients w/o assessments as all your joins are inner or we could use OUTER APPPLY to be sure to keep all answers regardless if an assessment has been provided.
Alternatively you could use a row_number() logic ( Tab Alleman's link has this covered) and a cte; but if cross apply is available might as well use it here.
Please include order by PTA.ASSESSMENT_DATE DESC to see the latest records at the top.

How get specific rows in grouped result

i need to group some data but because there are 4 store images , sql query return 4 result for every store. How can i get only one for a store by using sql query ?
select s.name,si.SHOP_IMG_PATH,count(*) amount from stab t
inner join shop s on (s.shop_id = t.shop_id)
inner join SHOP_IMG si on (s.shop_id= si.SHOP_ID)
where t.acct_id = 111 and t.CR_DATE >= sysDate - 1
group by s.name,si.SHOP_IMG_PATH
order by 3 desc,1 asc
As you see below image there a re 4 images so query can give random image
You are grouping by s.name, si.SHOP_IMG_PATH it will consider all possible combination of s.name, si.SHOP_IMG_PATH as separate you need to keep group by only s.name
Try this
SELECT a.NAME, a.PATH, a.AMOUNT
FROM (select
s.name AS 'NAME', si.SHOP_IMG_PATH AS 'PATH', count(*) AS 'AMOUNT',
ROW_NUMBER() OVER(PARTITION BY s.name
ORDER BY type si.SHOP_IMG_PATH) AS rk
from
stab t
inner join shop s on (s.shop_id = t.shop_id)
inner join SHOP_IMG si on (s.shop_id= si.SHOP_ID)
where t.acct_id = 111 and t.CR_DATE >= sysDate - 1
group by s.name
order by 3 desc,1 asc) a
WHERE a.rk = 1;
Alternative
You will get result but this is just a workaround and easy alternative to your problem but not a good one.
select s.name AS 'NAME', min(si.SHOP_IMG_PATH) AS 'PATH', count(*) AS 'AMOUNT',
from
stab t
inner join shop s on (s.shop_id = t.shop_id)
inner join SHOP_IMG si on (s.shop_id= si.SHOP_ID)
where t.acct_id = 111 and t.CR_DATE >= sysDate - 1
group by s.name
order by 3 desc,1 asc
This second query will return result as per your need
group by s.name, si.SHOP_IMG_PATH
You're telling it to differentiate them according to SHOP_IMG_PATH. Hence, it shows 4 results, one for each of those.
You'll have to drop SHOP_IMG_PATH from the select clause, if you won't let it use it.
Edit
Got your comment. What you're looking for is random aggregation. This is achieved diferently on different SQL engines. Google around for the one you're using.
If it's Oracle, as indicated by the question tag, here
I solved my problem by using below query,
select s.name,t.shop_id,(select min(SHOP_IMG_PATH) from SHOP_IMG si where shop_id =t.shop_id),count(*) amount from stab t
inner join shop s on (s.shop_id = t.shop_id)
where t.acct_id = 111 and t.CR_DATE >= sysDate - 1
group by s.name,t.shop_id
order by 4 desc,1 asc