我在mysql数据库上有两个表vendor
和medicines
现在我需要计算基于供应商ID交易的总药品,条件状态等于付费,在一个查询中并显示给我的用户
我的供应商表格看起来像这样
| ID | vendor_name |
+----+------------------+
| 1 | Marakel Medicine |
| 2 | Ignacio Pharmacy |
| 3 | Rico Medicines |
| 4 | Marco Pharmacy |
+----+------------------+
My Medicines表格如下所示。
| ID | vendor_id | medicine_name | Status |
+----+-----------+----------------+---------+
| 1 | 1 | paracetamol #1 | paid |
| 2 | 1 | paracetamol #1 | paid |
| 3 | 2 | paracetamol #1 | pending |
| 4 | 2 | paracetamol #1 | paid |
| 5 | 4 | paracetamol #1 | paid |
+----+-----------+----------------+---------+
我的愿望输出就像这样
+----+------------------+-----------+
| ID | vendor_name | Total Med |
+----+------------------+-----------+
| 1 | Marakel Medicine | 2 |
| 2 | Ignacio Pharmacy | 1 |
| 3 | Rico Medicines | 0 |
| 4 | Marco Pharmacy | 1 |
+----+------------------+-----------+
到目前为止我的代码在下面我能够按照供应商输出我只是不知道如何根据状态计算它们,任何建议都会很棒!
SELECT * FROM vendors LEFT JOIN medicine ON vendor.ID = medicines.vendor_id
答案 0 :(得分:2)
根据状态 [付费或待处理]& 供应商名称:
提议的查询:
SELECT vendor.ID, vendor.vendor_name,
COUNT((CASE WHEN [status] <> 'pending' THEN 1 END)) AS 'Total Med'
FROM medicines RIGHT OUTER JOIN
vendor ON medicines.vendor_id = vendor.ID
GROUP BY vendor.vendor_name, vendor.ID
注意: 这个查询已在MSSQL中得到解决,您可以参考逻辑并尝试MySQL。
对应的 MySQL 语法:
SELECT vendor.ID, vendor.vendor_name,
COUNT((CASE WHEN status <> 'pending' THEN 1 END)) AS 'Total Med'
FROM medicines
RIGHT OUTER JOIN vendor ON
medicines.vendor_id = vendor.ID GROUP BY vendor.vendor_name, vendor.ID
答案 1 :(得分:1)
使用GROUP BY
和COUNT
SELECT
v.ID,
v.vendor_name,
COUNT(m.vendor_id) AS 'Total Med'
FROM
vendors v
LEFT JOIN medicine m ON v.ID = m.vendor_id
GROUP BY
v.ID
答案 2 :(得分:1)
你应该试试这个
SELECT v.ID,v.vendor_name,COUNT(m.ID) as `Total`
FROM vendor v LEFT JOIN medicines m ON v.ID=m.vendor_id
GROUP BY m.ID
答案 3 :(得分:1)
@ tharif的MSSQL解决方案的MYSQL版本。
SELECT
v.ID,
v.vendor_name,
COUNT((CASE WHEN m.`status` <> 'pending' THEN 1 END)) AS 'Total Med'
FROM
vendor v
LEFT JOIN medicines m ON v.ID = m.vendor_id
GROUP BY v.ID
答案 4 :(得分:0)
使用Group通过它的sql函数并使用count也是一个内置函数的sql。类似如下所示。
SELECT vendors.id,vendors.vendor_name,COUNT(medicine.vendor_id) AS 'Total Transaction'
FROM vendors LEFT JOIN medicine ON vendors.id = medicine.vendor_id
GROUP BY vendors.id