在同一个表中选择多个列

时间:2015-01-07 12:26:54

标签: mysql sql

我不知道这是不是正确的问题。

我有一张包含两个字段的表格,即信用卡和借记卡。 我对每个字段进行总结,然后创建一个具有总余额的新列。 我创建了几个单独工作的查询 是这样的:

SELECT Sum(libromayor.debe) AS IngresosGlobal,
Sum(libromayor.haber) AS GastosGlobal,           
(Sum(libromayor.debe) - Sum(libromayor.haber)) AS TotalGlobal
FROM libromayor

和此:

SELECT Sum(libromayor.debe) AS IngresosActual,
Sum(libromayor.haber) AS GastosActual,
(Sum(libromayor.debe) - Sum(libromayor.haber)) AS TotalActual
FROM libromayor
WHERE Year(libromayor.fechaevento) = Year(CurDate()) 

我想要的是联合两个查询,但是在这种情况下将结果保留在6列中,而不是像在此查询尝试中那样3:

SELECT Sum(libromayor.debe) AS IngresosGlobal,
Sum(libromayor.haber) AS GastosGlobal,           
(Sum(libromayor.debe) - Sum(libromayor.haber)) AS TotalGlobal
FROM libromayor
UNION 
SELECT Sum(libromayor.debe) AS IngresosActual,
Sum(libromayor.haber) AS GastosActual,
(Sum(libromayor.debe) - Sum(libromayor.haber)) AS TotalActual
FROM libromayor
WHERE Year(libromayor.fechaevento) = Year(CurDate())  

给出的结果是:

IngresosGlobal   GastosGlobal   TotalGlobal
1521.00            1575.00        -54.00
121.00              100.00         21.00

但我想创建一个提供此结果的VIEW

IngresosGlobal   GastosGlobal   TotalGlobal     IngresosActual     GastosActual     TotalActual
1521.00            1575.00        -54.00           121.00              100.00           21.00

1 个答案:

答案 0 :(得分:1)

你可以这样做:

SELECT Sum(libromayor.debe) AS IngresosGlobal,
sum(IF(ear(libromayor.fechaevento) = Year(CurDate()), libromayor.debe, 0)) AS IngresosGlobal2
FROM libromayor

P.S。只显示一列,给你一个想法