mysql - 显示特定日期的数据?

标签 mysql sql date join union

I am trying to make a reporting system where I need to display report for each date.

enter image description here

These is my table schema for selected_items enter image description here This is stock_listenter image description here

I am using php in the back-end and java in the front end to display the data. I tried a couple of queries to get the desired output but so far I am not able to get it.These are some of the queries i used.

SELECT
   COALESCE(stock_list.date, selected_items.date) AS date,
   SUM( stock_list.qty ) AS StockSum,
   SUM( stock_list.weight ) AS Stockweight,
   COUNT( selected_items.barcode ) AS BilledItems,
   SUM( selected_items.weight ) AS Billedweight
FROM stock_list join selected_items
ON stock_list.date = selected_items.date
GROUP BY COALESCE(stock_list.date, selected_items.date)
ORDER BY COALESCE(stock_list.date, selected_items.date);

This gives me the first five columns but the output gives me wrong values. Then I also tried Union.

SELECT SUM( qty ) AS StockSum, SUM( weight ) AS Stockweight
FROM  `stock_list` 
WHERE DATE LIKE  '08-Jan-2016'
UNION SELECT COUNT( barcode ) AS BilledItems, SUM( weight ) AS Billedweight
FROM  `selected_items` 
WHERE DATE LIKE  '08-Jan-2016'
UNION SELECT SUM( qty ) AS TotalStock, SUM( weight ) AS TotalWeight
FROM  `stock_list`;

Here I get the correct values for four columns but the problem is the >result is displayed in two columns when I would like it to be in 4 columns. Can anyone guide me please I have figured the java part of it but I am not good at php and mysql. Thank you

最佳答案

不幸的是,当我尝试执行此查询时,SQL Fiddle 崩溃了

SELECT sl.date AS date, B.qtySum AS StockSum, B.weightSum AS Stockweight,
C.barcodeCount AS BilledItems, C.weightSum AS Billedweight
FROM stock_list sl 
JOIN (SELECT SUM(qty) as qtySum, SUM(weight) as weightSum
      FROM STOCK_LIST GROUP BY date) AS B
ON B.date = sl.date
JOIN (SELECT SUM (weight) AS weightSum, COUNT(barcode) AS barcodeCount
      FROM SELECTED_ITEMS GROUP BY date) AS C
ON C.date = sl.date;

As it was tried here .连接的问题是行将被多次连接,因此总和会出错。例如,您有四行从第二个表连接,因此总和应该高四倍。使用子查询,您可以避免这个问题,因为您在加入变量之前对变量进行计数和求和,因此数字应该合适。唉,我无法运行查询,所以我不能 100% 确定它是否有效,但它应该是正确的方法。

关于mysql - 显示特定日期的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34894655/

相关文章:

mysql - 仅允许通过特定应用程序连接 DBMS 用户

php - 如何用mysql更新设置的记录数?

sql - 如何从 View 中删除列

mysql - 如何将数据库表字段中的 CSV 与也包含逗号分隔值的变量进行比较?

r - 计算日期滞后

forms - 提交 Spring 表单时日期格式错误

java - 在 Java 中格式化时间戳

php - 特定优惠券的 Woocommerce 总销售额

PHP OOP 数据库连接

sql - 为什么我不能将唯一标识符/GUID 传递给存储过程