简体   繁体   中英

Count Case Statement - When One Field Greater Than Another

I'm trying to determine how pervasive a particular mistake is in my database. I'm comparing one field against another, and when that field is greater then the other, I want it to count it. I'm also grouping it by a different statement. The purpose of this query is to determine where there are cases in my data base when one price field is larger then another.

The part of the query that is causing problems is "COUNT(CASE when p.IMAP > p.MSRP = 1 ELSE NULL END)" in the select statement. I put two little stars around it, hoping that'd help highlight where it is.

select b.brandName, b.BrandCode, p.ProductVendorStockNumber, **COUNT(Case When p.IMAP > p.MSRP = 1 ELSE NULL END) as 'Count'**
from products p
join brands b on p.brandID = b.brandID 
where b.assignedTo = 'Steve' and p.IMAP > p.MSRP and status = 1
GROUP BY b.BrandName

For the count value You could use sum instead of count adding 1 when the condition is true and 0 when false

In sql for aggregated select the select for columns not in aggregated function and not mentioned in group by is deprecated, in the most recent version of mmysql is not allowed and for the older version the result for these values in unpredicatble so you should in group by then column that you have not in aggregation function in select eg:

    select b.brandName
        , b.BrandCode
        , p.ProductVendorStockNumber
        ,sum(Case When p.IMAP > p.MSRP THEN 1 ELSE 0  END) as my_count
    from products p
    join brands b on p.brandID = b.brandID 
    where b.assignedTo = 'Steve' and p.IMAP > p.MSRP and status = 1
    GROUP BY b.BrandName, b.BrandCode,  p.ProductVendorStockNumber

or filter the result using the rows without aggregation and a join on the right aggregated rows

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