为每个实验室计算计算机

时间:2010-03-22 21:58:03

标签: c# sql

好吧,我不得不计算来自不同实验室的PC和Mac。在每个实验中,我需要显示有多少PC和Mac可用。数据来自SQL服务器,正在尝试子查询和使用union,这是我能得到的最接近的东西。

下面的查询向我展示了两个不同列中的PC和Mac的数量,但当然,PC将在一行中,而Mac在另一行下面。让实验室出现两次。

EX:

LabName --  PC  /  MAC

Lab1  --     5   /   0

Lab1   --    0    /  2

查询

SELECT 
Labs.LabName, COUNT(*),0 AS Mac


FROM
HardWare INNER JOIN Labs ON HardWare.LabID = Labs.LabID

WHERE ComputerStatus = 'AVAILABLE'

GROUP BY Labs.LabName

UNION

SELECT
Labs.LabName, COUNT(*), (SELECT COUNT(Manufacturer)) AS Mac

FROM 
HardWare INNER JOIN Labs ON HardWare.LabID = Labs.LabID

WHERE ComputerStatus = 'AVAILABLE' AND Manufacturer = 'Apple'

GROUP BY Labs.LabName

ORDER BY Labs.LabName

那么有没有办法将它们放在一行中,如

Lab1 -- 5 / 2

或者是否有不同的方式来编写查询?

任何事都会有很大的帮助,我几乎被困在这里。

干杯

2 个答案:

答案 0 :(得分:1)

从头顶(未选中)简单,可能需要一些语法修复。

SELECT Labs.LabName, 
SUM (CASE WHEN Manufacturer = 'Apple' THEN 1 ELSE 0 END) AS 'MAC',
SUM (CASE WHEN Manufacturer != 'Apple' THEN 1 ELSE 0 END) AS 'PC'

FROM HardWare 
INNER JOIN Labs ON HardWare.LabID = Labs.LabID
WHERE ComputerStatus = 'AVAILABLE'
GROUP BY Labs.LabName
ORDER BY Labs.LabName

答案 1 :(得分:0)

实现您正在寻找的内容的一般子查询语法可能是这样的:

Select 
    labName, 
    (SELECT 
        COUNT(*) 
    FROM hardware 
    WHERE
        hardware.lab = lab.id
        AND type = 'pc'
        AND status = 'available'
    ) as PC, 
    (SELECT 
        COUNT(*) 
    FROM hardware 
    WHERE
        hardware.lab = lab.id
        AND type = 'mac'
        AND status = 'available'
    ) as Mac,
FROM
    labs