多表联查统计条数的SQL如何写?

举例如下,查询一个关联A,B,C三个表的数据,统计满足下面条件的总和(比如 count,sum),如何写?

SELECT 
A.dateNo + A.szNo AS SZId,
'1' AS difCode,
B.userId + B.shop AS userInfo,
C.total * 10 / 100 AS Account
FROM rj_Table A INNER JOIN sz_Table B ON A.dateNo = B.dateNo AND A.szId = B.zsId
INNER JOIN ms_Table C ON A.dateNo = C.dateNo AND a.szId = C.szId.
WHERE data >= '2024-1-1'
阅读 345
avatarAI BotBETA
为了统计多表联查后的数据条数,可以使用 `COUNT` 函数。以下是如何修改你的 SQL 查询以统计满足条件的记录总数:

SELECT

COUNT(*) AS totalCount

FROM

rj_Table A 

INNER JOIN

sz_Table B 
ON A.dateNo = B.dateNo AND A.szId = B.zsId

INNER JOIN

ms_Table C 
ON A.dateNo = C.dateNo AND A.szId = C.szId

WHERE

A.dateNo >= '2024-1-1';

这个查询将返回满足 `WHERE` 条件(即 `A.dateNo >= '2024-1-1'`)的记录总数。

如果你需要统计特定字段的总和,可以使用 `SUM` 函数。例如,如果你想要计算 `C.total * 10 / 100` 的总和,可以这样写:

SELECT

SUM(C.total * 10 / 100) AS totalAccount

FROM

rj_Table A 

INNER JOIN

sz_Table B 
ON A.dateNo = B.dateNo AND A.szId = B.zsId

INNER JOIN

ms_Table C 
ON A.dateNo = C.dateNo AND A.szId = C.szId

WHERE

A.dateNo >= '2024-1-1';

这个查询将返回 `C.total * 10 / 100` 的总和,满足同样的 `WHERE` 条件。
1 个回答
SELECT 
    A.dateNo + A.szNo AS SZId,
    '1' AS difCode,
    B.userId + B.shop AS userInfo,
    (C.total * 10 / 100) AS Account,
    COUNT(*) AS totalCount,
    SUM(C.total) AS totalSum
FROM 
    rj_Table A 
INNER JOIN 
    sz_Table B ON A.dateNo = B.dateNo AND A.szId = B.zsId
INNER JOIN 
    ms_Table C ON A.dateNo = C.dateNo AND A.szId = C.szId
WHERE 
    A.dateNo >= '2024-01-01'
GROUP BY 
    SZId, difCode, userInfo, Account;

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏