0

我有以下查询总是给我两行。我想使用 tbluser.userid 将它们分组到一行,是否可以将联合分组?

SELECT
SUM(tblfooditem.calories)
FROM tblfooditem
INNER JOIN tbluser ON tblfooditem.userid = tbluser.userid
WHERE tblfooditem.userid=?userid AND tblfooditem.date=?date
GROUP BY tbluser.userid
UNION
SELECT
SUM(tbladdedmealitem.calories)
FROM tbladdedmeal
INNER JOIN tbluser ON tbladdedmeal.userid = tbluser.userid
WHERE tbladdedmeal.userid=?userid AND tbladdedmeal.date=?date
GROUP BY tbluser.userid;
4

1 回答 1

3

这是可能的。

select sum(s) from (
SELECT
    SUM(tblfooditem.calories) S,tbl.userid
    FROM tblfooditem
    INNER JOIN tbluser ON tblfooditem.userid = tbluser.userid
    WHERE tblfooditem.userid=?userid AND tblfooditem.date=?date
    GROUP BY tbluser.userid
    UNION
    SELECT
    SUM(tbladdedmealitem.calories) S,tbl.userid
    FROM tbladdedmeal
    INNER JOIN tbluser ON tbladdedmeal.userid = tbluser.userid
    WHERE tbladdedmeal.userid=?userid AND tbladdedmeal.date=?date
    GROUP BY tbluser.userid
) Q
group by Q.userid
于 2009-04-18T09:41:37.217 回答