我有两张桌子
一个表连接“客户ID”和“产品ID”
TABLE A
ClientID ProductID
1 2
1 4
1 6
2 3
2 5
然后还有另一个表记录了产品花费的时间:
TABLE B
ProductID Time Date_added
2 10 (datetime)
4 2 (datetime)
2 3 (datetime)
4 1 (datetime)
如何组合两个查询:
获取与客户关联的所有产品ID的一个查询
SELECT ProductID FROM TABLE_A where ClientID = 1
然后每月获得这些产品的所有时间总和?
SELECT SUM(time) from Table_B WHERE DATEPART(month, Date_added) = 8 AND ProductID = (products from the previous query?)
答案 0 :(得分:3)
听起来你想要一个连接声明,在黑暗中拍摄但可能
SELECT A.ClientID,SUM(B.Time)
FROM
TABLE A AS A
LEFT JOIN
TABLE B AS B ON (A.ProductID = B.ProductID)
WHERE
DATEPART(month, B.Date_added) = 8
GROUP BY
A.ClientID
这将显示按客户端ID分组的所有产品的总时间。这还包括那些没有时间花在本月产品上的客户
答案 1 :(得分:0)
你真的很亲密。
SELECT SUM(B.time)
FROM Table_B B INNER JOIN
Table_A A ON B.ProductID = A.ProductID
WHERE DATEPART(month, B.Date_added) = 8
AND A.ClientID = 1
;
答案 2 :(得分:0)
SELECT SUM(time) from Table_B
WHERE DATEPART(month, Date_added) = 8
AND ProductID IN (SELECT ProductID FROM TABLE_A where ClientID = 1)
答案 3 :(得分:0)
SELECT SUM(time)
FROM B
Join A on A.productID = B.ProductID
WHERE where a.clientID =1
group my month(b.date);