SQL相当新,但我试图从同一个表中获得2个选择查询之间的区别。我试过以下
SELECT
(SELECT KwhMeter,IndexElek,CalorieMeter,IndexWarmte,IndexWarmWater,IndexKoudWater,Date FROM Energiemeters WHERE Date = '2017-05-01')
-
(SELECT KwhMeter,IndexElek,CalorieMeter,IndexWarmte,IndexWarmWater,IndexKoudWater,Date FROM Energiemeters WHERE Date = '2017-04-01') AS Difference
但我最终得到以下错误:
#1241 - Operand should contain 1 column(s)
答案 0 :(得分:0)
如果您想要5月1日但不是4月1日的行,那么一种方法是使用聚合:
SELECT KwhMeter, IndexElek, CalorieMeter, IndexWarmte, IndexWarmWater, IndexKoudWater, Date
FROM Energiemeters
WHERE Date IN ('2017-04-01', '2017-05-01')
GROUP BY KwhMeter, IndexElek, CalorieMeter, IndexWarmte, IndexWarmWater, IndexKoudWater
HAVING MIN(Date) = '2017-05-01';
答案 1 :(得分:0)
使用Cross Join
。这是假设每个日期只得到一行。
Select
(a.KwhMeter-b.KwhMeter) as KwhMeter,
(a.IndexElek-b.IndexElek) as IndexElek,
(a.CalorieMeter-b.CalorieMeter) CalorieMeter,
(a.IndexWarmte-b.IndexWarmte) IndexWarmte,
(a.IndexWarmWater-b.IndexWarmWater) IndexWarmWater,
(a.IndexKoudWater-b.IndexKoudWater) IndexKoudWater,
(a.Date-b.Date) as Date
from
(
SELECT distinct KwhMeter,IndexElek,CalorieMeter,IndexWarmte,IndexWarmWater,IndexKoudWater,Date
FROM Energiemeters
WHERE Date = '2017-05-01'
) a
cross join
(
SELECT distinct KwhMeter,IndexElek,CalorieMeter,IndexWarmte,IndexWarmWater,IndexKoudWater,Date
FROM Energiemeters
WHERE Date = '2017-04-01'
) b;
答案 2 :(得分:0)
好像你想从日期2017-05-01
和2017-04-01
确定的两行中减去相应的列值?
如果是,则查询可以写成如下:
SELECT SUM(CASE Date
WHEN '2017-05-01' THEN KwhMeter
WHEN '2017-04-01' THEN -KwhMeter
END) AS KwhMeter,
SUM(CASE Date
WHEN '2017-05-01' THEN IndexElek
WHEN '2017-04-01' THEN -IndexElek
END) AS IndexElek,
SUM(CASE Date
WHEN '2017-05-01' THEN CalorieMeter
WHEN '2017-04-01' THEN -CalorieMeter
END) AS CalorieMeter,
SUM(CASE Date
WHEN '2017-05-01' THEN IndexWarmte
WHEN '2017-04-01' THEN -IndexWarmte
END) AS IndexWarmte,
SUM(CASE Date
WHEN '2017-05-01' THEN IndexWarmWater
WHEN '2017-04-01' THEN -IndexWarmWater
END) AS IndexWarmte,
SUM(CASE Date
WHEN '2017-05-01' THEN IndexKoudWater
WHEN '2017-04-01' THEN -IndexKoudWater
END) AS IndexKoudWater
FROM Energiemeters
WHERE Date IN ('2017-05-01', '2017-04-01')
可以找到小型工作演示here。
答案 3 :(得分:-1)
在大多数RDBMS中工作,除了MYSQL:
如果我想计算每列差异,我会使用公共表表达式来准备子结果,然后计算差异。
WITH
res1 AS
(SELECT KwhMeter,IndexElek,CalorieMeter,IndexWarmte,IndexWarmWater,IndexKoudWater,Date FROM Energiemeters WHERE Date = '2017-05-01'),
res2 AS
(SELECT KwhMeter,IndexElek,CalorieMeter,IndexWarmte,IndexWarmWater,IndexKoudWater,Date FROM Energiemeters WHERE Date = '2017-04-01')
SELECT
r1.KwhMeter - r2.KwhMeter, r1.OtherColumnName - r2.OtherColumnName ... FROM res1 r1, res2 r2
但是......每个子选择(日期)一行完美。你是否保证每个日期有一个条目?那是PK吗?您需要指定您的问题,主要是“差异”是什么意思。