简体   繁体   中英

SQL Server : Select in Select

I have something like this:

Select
    sum(spareparts), 
    month(calculationdate) 
from 
    cz_axnmrs_calculations 
where 
    CASE_ID in (select case_id 
                from cz_axnmrs_cases 
                where insurer_memberid = 'MM-O-5B57274F') 
    and YEAR(calculationdate)='2014'  
group by 
    month(calculationdate) DESC

It's cool but i need to edit it a bit more specific. Right it get data from all spareparts, and I need to get it just from LAST ONE! So instead of that to count 3 results via SUM just display LAST one

I try write one more select to sum brackets but it finish with error SQL syntax. Can somebody help me to write this statement?

Thanks

尝试将TOP 1添加到第一个SELECT

if you mean last one from the result you already got then-

SELECT TOP 1
    sum(spareparts), 
    month(calculationdate) 
from 
    cz_axnmrs_calculations 
where 
    CASE_ID in (select case_id 
                from cz_axnmrs_cases 
                where insurer_memberid = 'MM-O-5B57274F') 
    and YEAR(calculationdate)='2014'  
group by 
    month(calculationdate) 
ORDER month(calculationdate) desc

Either

SELECT TOP 1
    sum(spareparts), 
    month(calculationdate) 
FROM
    cz_axnmrs_calculations 
WHERE
    CASE_ID in (select case_id 
                from cz_axnmrs_cases 
                where insurer_memberid = 'MM-O-5B57274F') 
    and YEAR(calculationdate)='2014'  
GROU BVY 
    month(calculationdate) DESC

Or add another vale to the group by.... Memberid

If showing last row is what you want to do you can try these:

Use Order by <column> desc and then pick the 1st row using Top 1 .

You can also use ROW_NUMBER()

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