我正在开发一个需要嵌入式数据库的应用程序,所以我使用MYSQL设计它,并创建了一个可以在那里工作的SQL语句。但是,当移动到嵌入式数据库(即Hyper-SQL(HSQLDB))时,我的查询不再起作用。它似乎与我在选择中必须与Group By匹配的参数数量有关,但是如果我去添加它们,它会保持数据未分组并且对我不起作用。
以下是查询:
我有两个表(GFS和SUPP)具有相同的列,不同之处在于行为,而另一个表的填充列更多。
SELECT gfs.GFSAccount, gfs.GLAccount,
CASE
WHEN gfs.ICPartner = "" THEN '[ICP_NONE]'
WHEN gfs.ICPartner <> "" THEN gfs.ICPartner
END AS ICPartner,
CASE
WHEN gfs.PPESupplementalData <> '' THEN gfs.PPESupplementalData
WHEN gfs.PPESupplementalData = '' THEN '[NONE]'
END AS SupplementalData,
CASE
WHEN gfs.AccountType = 'SALES AND COS' THEN gfs.PCode
WHEN gfs.AccountType = 'COO' THEN 'COO'
WHEN gfs.AccountType = 'OTHERS' THEN gfs.Business
END AS Business,
Round(Sum(gfs.Amount), 2) AS Amount
FROM gfs, supp
WHERE gfs.GLAccount <> supp.GLAccount
GROUP BY gfs.GFSAccount,
CASE WHEN gfs.ICPartnerSplit = 1 THEN gfs.ICPartner END
UNION
SELECT GFSAccount, GLAccount,
CASE
WHEN ICPartner = "" THEN '[ICP_NONE]'
WHEN ICPartner <> "" THEN ICPartner
END AS ICPartner,
CASE
WHEN SuppData <> '' THEN SuppData
WHEN SuppData = '' THEN '[NONE]'
END AS SupplementalData,
Business, Round(Sum(Amount), 2) AS Amount
FROM supp
ORDER BY GFSAccount;
对于空白和固定字段进行了大量转换,但主要问题是3组(每个选项中有2个,最后一个),它不允许我去做。
(我知道查询本身并不是最好的创建或优化,但我已经从数据库中暂时停止了一段时间,而且我有点生疏了)
为了让它能在HSQLDB中工作(或者不是MySQL的另一个数据库),你们有什么建议吗?
答案 0 :(得分:1)
出现您要从gfs
表中选择数据,但前提是GLAccount
表中不存在supp
。您需要LEFT JOIN
来执行此操作。否则,您需要GROUP BY
sum()
函数中未使用的所有列。您可以简化CASE
语句。对于PostgreSQL,查询看起来像这样:
SELECT gfs.GFSAccount, gfs.GLAccount,
CASE gfs.ICPartner
WHEN '' THEN '[ICP_NONE]' ELSE gfs.ICPartner
END AS ICPartner,
CASE gfs.PPESupplementalData
WHEN '' THEN '[NONE]' ELSE gfs.PPESupplementalData
END AS SupplementalData,
CASE gfs.AccountType
WHEN 'SALES AND COS' THEN gfs.PCode
WHEN 'COO' THEN 'COO'
WHEN 'OTHERS' THEN gfs.Business
END AS Business,
round(sum(gfs.Amount), 2) AS Amount
FROM gfs
LEFT JOIN supp USING (GLAccount)
WHERE supp.GLAccount IS NULL
GROUP BY 1, 2, 3, 4, 5, 6
UNION
SELECT GFSAccount, GLAccount,
CASE ICPartner
WHEN '' THEN '[ICP_NONE]' ELSE ICPartner
END AS ICPartner,
CASE SuppData
WHEN '' THEN '[NONE]' ELSE SuppData
END AS SupplementalData,
Business, round(sum(Amount), 2) AS Amount
FROM supp
GROUP BY 1, 2, 3, 4, 5, 6
ORDER BY GFSAccount;
如果各列为NULL
而不是空字符串''
,则应将CASE
语句更改为coalesce(gfs.ICPartner, '[ICP_NONE]') AS ICPartner
等。