我可以在 MySQL 中将 Distinct 与 Union All 一起使用吗?
Can I use Distinct with Union All in MySQL?
我正在使用 UNION ALL
从不同的表中获取值。
我的代码如下。
SELECT DISTINCT datei, amount FROM
(
SELECT datei, amount, 1 AS identification FROM income
UNION ALL
SELECT datee, amount, 2 AS identification FROM expense
UNION ALL
SELECT date, amount, 3 AS identification FROM others
) t
ORDER BY `datei` ASC
但我希望它是 distinct
的日期。
那我该怎么做呢?
提前致谢。
SELECT datei, sum(amount)
FROM
(
SELECT datei, amount, 1 AS identification FROM income
UNION ALL
SELECT datee, amount, 2 AS identification FROM expense
UNION ALL
SELECT date, amount, 3 AS identification FROM others
) t
GROUP BY datei
ORDER BY datei ASC
要获取日期的单笔金额,您可以使用以下查询
SELECT datei,SUBSTRING_INDEX(GROUP_CONCAT(amount),',',1) amount
FROM (
SELECT datei,amount, 1 AS identification FROM income
UNION ALL
SELECT datee,amount, 2 AS identification FROM expense
UNION ALL
SELECT DATE,amount, 3 AS identification FROM others
) t
GROUP BY datei
ORDER BY `datei` ASC
我正在使用 UNION ALL
从不同的表中获取值。
我的代码如下。
SELECT DISTINCT datei, amount FROM
(
SELECT datei, amount, 1 AS identification FROM income
UNION ALL
SELECT datee, amount, 2 AS identification FROM expense
UNION ALL
SELECT date, amount, 3 AS identification FROM others
) t
ORDER BY `datei` ASC
但我希望它是 distinct
的日期。
那我该怎么做呢?
提前致谢。
SELECT datei, sum(amount)
FROM
(
SELECT datei, amount, 1 AS identification FROM income
UNION ALL
SELECT datee, amount, 2 AS identification FROM expense
UNION ALL
SELECT date, amount, 3 AS identification FROM others
) t
GROUP BY datei
ORDER BY datei ASC
要获取日期的单笔金额,您可以使用以下查询
SELECT datei,SUBSTRING_INDEX(GROUP_CONCAT(amount),',',1) amount
FROM (
SELECT datei,amount, 1 AS identification FROM income
UNION ALL
SELECT datee,amount, 2 AS identification FROM expense
UNION ALL
SELECT DATE,amount, 3 AS identification FROM others
) t
GROUP BY datei
ORDER BY `datei` ASC