SQL%的数据包含值

时间:2017-02-08 18:33:06

标签: sql

我有一个Microsoft SQL表,其中包含organization列和mi_status列,两者都是字符串。我想找出每个(按分组)组织有多少记录有mi -status的“有库存”,有多少总记录,然后有多少记录有库存。

我可以通过以下方式轻松获得In Stock部分:

SELECT organization, count(*)
FROM table
WHERE mi_status = 'In Stock'
GROUP BY organiztion

但我不知道如何在同一个选择中获取总行数,因为我在那里有'where'子句。

3 个答案:

答案 0 :(得分:3)

使用条件聚合:

SELECT organization, count(*) as total,
       SUM(CASE WHEN mi_status = 'In Stock' THEN 1 ELSE 0 END) as total_instock,
       AVG(CASE WHEN mi_status = 'In Stock' THEN 1.0 ELSE 0 END) as proportion_instock
FROM table
GROUP BY organization;

答案 1 :(得分:2)

使用CASE表达式:

SELECT  organization, 
        SUM(CASE WHEN mi_status = 'In Stock' THEN 1 ELSE 0 END) In_Stock,
        COUNT(*) Total,
        SUM(CASE WHEN mi_status = 'In Stock' THEN 1 ELSE 0 END)*100.0/COUNT(*) Percentage
FROM dbo.YourTable
GROUP BY organization;

答案 2 :(得分:0)

SELECT 
    organization, 
    count(*), 
    (SELECT COUNT(*) FROM table) as total
FROM 
    table
WHERE 
    mi_status = 'In Stock'
GROUP BY 
    organization