简体   繁体   中英

SQL Server sub-query

I am trying write a query to show the number of refill txn and number and # unique pts in a 10 day period but is running into some errors. I was wondering if you can offer some insight on what went wrong with my query.

I am hoping to get # of unique patient per each station but instead i am getting the same number for each row...

I believe there is something I missed in the sub-query section, but I can't seem to figure out what is wrong. Any thoughts?

SELECT
    QB.vw_Pocket.PocketName As StationName,
    COUNT(*) AS [# of refill txns],
    (SELECT COUNT(DISTINCT QB.vw_PocketAccess.PatientKey) AS [# of pt]
     FROM QB.vw_PocketAccess
     WHERE QB.vw_PocketAccess.ClientKey = 10273 
       AND QB.vw_PocketAccess.TransactionDateTime BETWEEN CONVERT(DATE, DATEADD(day, -10, GetDate())) 
                                                      AND CONVERT(DATE, DATEADD(day, 0, GetDate()))) AS [#of Pt]
FROM
    QB.vw_PocketAccess
INNER JOIN
    QB.vw_Med ON QB.vw_Med.MedKey = QB.vw_PocketAccess.MedKey
INNER JOIN
    QB.vw_Pocket ON QB.vw_Pocket.PocketKey = QB.vw_PocketAccess.PocketKey
INNER JOIN
    QB.vw_TransactionType ON QB.vw_PocketAccess.TransactionTypeKey = QB.vw_TransactionType.TransactionTypeKey
WHERE
    QB.vw_PocketAccess.ClientKey = 10273 
    AND QB.vw_Med.ClientKey = 10273    
    AND QB.vw_Pocket.ClientKey = 10273 
    AND QB.vw_PocketAccess.TransactionDateTime BETWEEN CONVERT(DATE, DATEADD(day, -10, GetDate())) 
                                                   AND CONVERT(DATE, DATEADD(day, 0, GetDate())) 
    AND QB.vw_PocketAccess.TransactionTypeKey = 3
GROUP BY
    QB.vw_Pocket.PocketName

You need to correlate the sub-query. Now your subquery will return just the count from vw_PocketAccess table with filters ClientKey = 10273 and TransactionDateTime BETWEEN CONVERT(DATE, DATEADD(day, -10, GetDate())) AND CONVERT(DATE, DATEADD(day, 0, GetDate()))

To make the sub-query to return per each station you need to link the subquery with outer query. Something like this.

( 
 SELECT Count(DISTINCT qb.vw_pocketaccess.patientkey) AS [# of pt] 
 FROM   qb.vw_pocketaccess  
 WHERE  qb.vw_pocketaccess.station = station from outer tables --replace with the staion column
 AND    qb.vw_pocketaccess.clientkey = 10273 
 AND    qb.vw_pocketaccess.transactiondatetime BETWEEN CONVERT(DATE, Dateadd(day, -10, Getdate()))
                         AND    CONVERT(DATE, Dateadd(day, 0, Getdate()))
) as [#of Pt]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM