[英]How to select All the rows from first table and get count of all the matching rows from other table for each row retrived from first table
以下是表格
表格1
price col1 col2 time
10 1 1 10
100 1 1 13
150 1 1 15
表2
id startTm endTm col1 col2
1 12 20 1 1
2 15 26 1 1
3 11 13 1 1
我希望表2中的所有行都满足startTm> = x和endTm <= y。 对于结果的每一行,我想查找表1中所有记录的计数,其中table1.time位于该特定行的startTm和endTm中
像这样的东西
SELECT (@sTime:=T2.startTm) AS startTm,JT.totalNo, JT.totalPrice,
(@eTime:=T2.endTm) AS endTm
some more columns FROM table 2 AS T2
LEFT JOIN (SELECT COUNT(id) AS totalNo,col1, col2 SUM(price) AS
totalPrice FROM table 1 WHERE time BETWEEN @sTime AND @eTime GROUP
BY col1, col2)
AS JT ON JT.col1 = T2.col1
WHERE T2.startTm >= some value AND T2.endTm <= some value.
没有相关的外键。我没有得到正确的结果。 怎么做?
编辑
我希望表2中的所有记录在指定的时间范围内假设startTm> = 10到endTm <= 20,因此输出表将是
startTm endTm totalNo totalPrice some more col
12 20 2 250 ...
11 13 1 100 ...
计算总价格和总数,我想考虑该特定行的startTm和endTime。
这是你想要的吗?
SELECT startTm, endTm, COUNT(price), SUM(price), t3_others, t1_others
FROM
(
SELECT T3.startTm AS startTm, T3.endTm AS endTm, T3.others AS t3_others, T1.price AS price, T1.others AS t1_others
FROM T1
RIGHT JOIN
(
SELECT T2.startTm, T2.endTm, T2.others
FROM T2
WHERE T2.startTm >= 10 AND T2.endTm <= 20 AND T2.col1 = col1_value AND T2.col2 = col2_value
) AS T3
ON T1.time >= T3.startTm AND T1.time <= T3.endTm
) AS T4
GROUP BY startTm, endTm;
根据需要添加其他更多字段。
尝试以下查询:
从表1中选择t1。*,t2。*作为t1右联接将表2选择为t2 ON t1.col1 = t2.col1 W2位置t2.startTm> ='您的值'AND t2.endTm <='您的值'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.