我试图找到一张包含4个表格的表格:clients
,groups_clients
,client_data1
,client_data2
;
客户端
clId| GroupId | Other |
------------------------
1 | 1 | gddgdg|
2 | 1 | dgdg |
3 | 2 | ddg |
4 | 2 | dd4g |
5 | 1 | ddg |
groups_clients
grId | GroupName|
-----------------
1 | Group1 |
2 | Group2 |
table_data1
clId | Date | Buy | Trade |
--------------------------------
1 | 2017-06-05 | 3 | 4 |
2 | 2017-11-10 | 6 | 9 |
2 | 2017-11-11 | 4 | 13 |
2 | 2017-03-01 | 11 | 0 |
4 | 2017-01-10 | 3 | 11 |
table_data2
clId | Date | With | Depos |
--------------------------------
1 | 2017-03-05 | 1 | 3 |
5 | 2017-08-10 | 0 | 8 |
2 | 2017-11-11 | 0 | 13 |
3 | 2017-03-01 | 11 | 0 |
4 | 2017-01-10 | 3 | 11 |
理想的表应该是这样的
GroupName | SUM(Buy) | SUM(Trade) | SUM(With) | SUM(Depos) |
------------------------------------------------------------
Group1 | 13 | 26 | 1 | 24 |
Group2 | 3 | 11 | 14 | 11 |
查询应该汇总从table_data1
获取的所有行以及table_data2
,其中日期为some date
并将其分组为group name
这是我的代码:
SELECT
groups_clients.GroupName as group_name,
clients.GroupId AS groupid,
SUM(table_data1.buy) AS buy,
SUM(table_data1.trade) AS trade,
with,
depos
FROM
table_data1
INNER JOIN
(SELECT
SUM(table_data2.with) AS with,
clients.clId, GroupId
FROM
clients
LEFT JOIN
table_data2 ON clients.clId = table_data2.clId
AND table_data2.date <= '11-11-2016'
GROUP BY
GroupId, clId) clients ON table_data1.clId = clients.clId
LEFT JOIN
groups_clients ON groups_clients.Id = clients.GroupId
WHERE
table_data1.date <= '11-11-2016'
GROUP BY
clients.GroupId, With, Depos,
groups_clients.GroupName
但结果有点可怕。它连续输出了很多相同的组,好像我没有按groupname
分组。伙计们,我需要你的帮助。有任何想法吗?我该怎么做才能使查询工作正常?提前谢谢!
答案 0 :(得分:1)
您必须预先对SUMS进行分组,然后加入以避免重复计算行。
DECLARE @mydate DATETIME
SELECT @mydate='11/11/2017'
SELECT gc.GroupName,
isnull(SUM([Buy]), 0) [Buy],
isnull(SUM([Trade]), 0) [Trade],
isnull(SUM([With]), 0) [With],
isnull(SUM([Depos]), 0) [Depos]
FROM groups_clients gc
INNER JOIN clients c ON gc.grId=c.GroupId
LEFT JOIN (SELECT clId, SUM([Buy]) [Buy], SUM([Trade])[Trade]
FROM table_data1 WHERE [Date]=@mydate GROUP BY clId) a ON c.clId=a.clId
LEFT JOIN (SELECT clId, SUM([With]) [With], SUM([Depos])[Depos]
FROM table_data2 WHERE [Date]=@mydate GROUP BY clId) b ON c.clId=b.clId
GROUP BY gc.GroupName
答案 1 :(得分:0)
您是否尝试过从group_client表开始..加入到客户端,然后加入table_data1和table_data2 ..然后聚合您想要的列?
所以查询会像这样
declare @date date = '2017-06-05'
select
gc.groupname
,sum(td1.buy) as total_buy
,sum(td1.Trade) as total_trade
,sum(td2.with) as total_with
,sum(td2.Depos) as total_depos
from groups_client gc
inner join clients c
on c.groupid = gc.grid
inner join table_data1 td1
on td1.clid = c.clid
and td1.Date = @date
inner join table_data2 td2
on td2.clid = c.clid
and td2.Date = @date
group by
gc.groupname