Journal_T
- 基本上这是具有正值和负值的日记表。
字段为:id
,date
,ref
,description
,amount
,segment
,period
,year
我想在两个单独的列中显示它 - debits
(包含正值)和credits
(包含负值)。以下是我正在使用的查询:
$qry = mysql_query("SELECT id, date, ref, description, SUM(amount),
segment, period, year
FROM Journal_T
GROUP BY segment, year, period, id") or die(mysql_error());
答案 0 :(得分:1)
SELECT
id,
date,
ref,
description,
SUM(CASE WHEN amount > 0 THEN Amount END) AS TotalPositive,
SUM(CASE WHEN amount < 0 THEN Amount END) AS TotalNegative,
segment,
period,
year
FROM Journal_T
GROUP BY segment, year, period, id
另一方面,我认为date
,ref
和description
的值在此查询的输出中没有多大意义,只要您不包括他们在GROUP BY列表中。 MySQL允许您将它们包含在SELECT列表中而不进行聚合,但是为这些列返回的值可能是任意的,并且与检索到的其他数据没有太大关系,特别是对于总和。
答案 1 :(得分:0)
如果我了解架构,请使用CASE
:
SELECT id,
date,
ref,
description,
CASE WHEN SUM(amount) >= 0 THEN SUM(amount) ELSE NULL END AS positive,
CASE WHEN SUM(amount) < 0 THEN SUM(amount) ELSE NULL END AS negative,
,segment,period,year FROM Journal_T GROUP BY segment,year,period,id