计算在日期范围之间输入到多个表的记录

时间:2013-09-18 06:01:32

标签: sql sql-server

Table 1
--------
landrepairID pk
workshopID fk
Date

Table 2
--------
searepairID pk
workshopID fk
Date

Table 3
--------
airrepairID pk
workshopID fk
Date

Table 4
--------
workshopID pk
workshop name

我想在研讨会ID分组的两个日期之间的所有三个表中检查进入车库的车辆数量。

如, 如果日期是2013年1月1日至2013年1月1日 结果应该是,

workshopID | count 
1             45
2             16

3 个答案:

答案 0 :(得分:0)

试试这个

SELECT workshopid, 
       Count(1) AS countall
FROM   (SELECT workshopid 
        FROM   table1 
        WHERE  date BETWEEN '1/1/2013' AND '1/2/2013' 
        UNION ALL 
        SELECT workshopid 
        FROM   table2 
        WHERE  date BETWEEN '1/1/2013' AND '1/2/2013' 
        UNION ALL 
        SELECT workshopid 
        FROM   table3 
        WHERE  date BETWEEN '1/1/2013' AND '1/2/2013') as all_data 
GROUP  BY workshopid 

答案 1 :(得分:0)

我自己遇到了这个问题,这是我提出的解决方案:

<form action="" method="post" name="submit">
<input type="date" name="begin"/>
<input type="date" name="end"/>
<input type="submit" name="submit" value="Submit"/>
</form>
<?php
error_reporting(0);
$start = strtotime($_POST['begin']);
$end = strtotime($_POST['end']);
 $con=mysqli_connect("localhost","user","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }
$result = mysqli_query($con,"SELECT user, SUM(1) FROM processed WHERE `date` BETWEEN FROM_UNIXTIME($start) AND FROM_UNIXTIME($end) GROUP BY first_name  ;" );

echo "<table border='1' class='data'>
<tr>

 <th>First Name</th>
<th>Last Name</th>
<th>Total Processed</th>
</tr>";

while($row = mysqli_fetch_array($result))
 {
 echo "<tr>";
 echo "<td>" . $row['first_name '] . "</td>";
 echo "<td>" . $row['last_name '] . "</td>";
 echo "<td>" . $row['numb'] . "</td>";
 echo "</tr>";
 }
echo "</table>";


mysqli_close($con);

?>

我不知道这会对您有多大帮助,但我进行了设置,以便您可以实际选择所需的日期,而不是在代码中使用硬值。

答案 2 :(得分:0)

试试这个:

DECLARE @DateFrom DATE, @DateTo DATE
SELECT  @DateFrom = '1/1/2013', @DateTo = '1/2/2013' 
SELECT workshopid, Cnt 
FROM   (SELECT workshopid, COUNT(*) AS Cnt
        FROM   table1 
        WHERE  date BETWEEN @DateFrom AND @DateTo
        UNION ALL 
        SELECT workshopid, COUNT(*) AS Cnt
        FROM   table2
        WHERE  date BETWEEN @DateFrom AND @DateTo
        UNION ALL 
        SELECT workshopid, COUNT(*) AS Cnt
        FROM   table3 
        WHERE  date BETWEEN @DateFrom AND @DateTo
) aggregated