如何在SQL中合并2行

时间:2011-08-03 15:36:04

标签: sql sql-server-2005 sql-server-2008

我正在尝试创建一个存储过程来从多个中检索值。问题出在表A中,有一个布尔类型(isLocked),我必须为每个状态创建一个列('Locked'和'Unlocked')。这是我写的查询:

SELECT    Machine.Machine_ID,
SUM(FinanceDonnee.CoutHoraire) AS Total,
CASE 
WHEN FinanceDonnee_isLocked = 1
 THEN
    SUM(FinanceDonnee.CoutHoraire)
 ELSE
    0
END
AS Locked,
CASE 
WHEN FinanceDonnee_isLocked= 0
 THEN
    SUM(FinanceDonnee.CoutHoraire)
 ELSE
    0
END
AS Unlocked
FROM         ICR INNER JOIN
             FinanceDonnee ON Machine.Machine_ID = FinanceDonnee.FinanceDonnee_Machine_ID
GROUP BY ICR_ID, FinanceDonnee.FinanceDonnee_isLocked

但它运作不正常,因为它复制了Machine_ID,一个用于锁定,另一个用于解锁:

ID          Locked   Unlocked
4D9646EC    0        2
4D9646EC    12       0

我想有这样的观点:

ID          Locked   Unlocked
4D9646EC    12       2

我该怎么做?

感谢。

1 个答案:

答案 0 :(得分:7)

只需锁定一个总和,解锁即可:

select sum(locked) as Locked ,sum(unlocked) as Unlocked, ID 
from tablea 
inner join tableb on tablea.ID=tableb.ID 
group by ID

使用你的sql,我认为这应该有效:

SELECT machine_id    AS id,
       SUM(locked)   AS locked,
       SUM(unlocked) AS unlocked
FROM   (SELECT machine.machine_id,
               SUM(financedonnee.couthoraire) AS total,
               CASE
                 WHEN financedonnee_islocked = 1 THEN SUM(
                 financedonnee.couthoraire)
                 ELSE 0
               END                            AS locked,
               CASE
                 WHEN financedonnee_islocked = 0 THEN SUM(
                 financedonnee.couthoraire)
                 ELSE 0
               END                            AS unlocked
        FROM   icr
               INNER JOIN financedonnee
                 ON machine.machine_id = financedonnee.financedonnee_machine_id
        GROUP  BY icr_id,
                  financedonnee.financedonnee_islocked) t
GROUP  BY t.machine_id