从库存中获取可用设备的SQL语句

时间:2014-09-17 02:26:02

标签: mysql sql sql-server

我有一个表equipment,其中列namedescriptionstatus

这是我显示所有行时表格的样子:

id  name      description   status
1   shovel    shiny shovel     1
2   shovel    shiny shovel     1
3   shovel    shiny shovel     0
4   hammer    big hammer       1
5   hammer    big hammer       0

这是我现在的SQL语句:

SELECT equipment.name, equipment.description, COUNT(*) AS stock 
FROM equipment 
GROUP BY equipment.name

它显示以下内容:

name    description   stock
shovel  shiny shovel    3
hammer  big hammer      2

我想要的是显示另一列,显示状态为1

的设备数量
name    description   stock  available
shovel  shiny shovel    3       2
hammer  big hammer      2       1

2 个答案:

答案 0 :(得分:4)

你几乎就在那里:你需要的只是总结状态字段,如下所示:

SELECT 
    equipment.name, 
    equipment.description, 
    COUNT(*) AS stock, 
    SUM(status) as available
FROM equipment 
GROUP BY 
    equipment.name,
    equipment.description

答案 1 :(得分:1)

这里的技巧(可在SQL Server和MySQL中使用)是使用条件SUM()代替COUNT()

    SELECT ..., SUM(WHEN CASE status = 1 THEN 1 ELSE 0 END) as available

如果status只能10,那么您可以将其合计:

    SELECT ..., SUM(status) as available