简体   繁体   English

SQL查询,从ID多次求和相同的条目

[英]SQL Query, Sum the same entry from ID multiple times

I first ran a query to get the item ID, 我首先运行查询以获取商品ID,

SELECT ITEM 
FROM `SALES` 
WHERE DATE>='2018-2-1' AND DATE<='2018-2-5' AND CASH_CREDIT='1'

Which returned the results; 返回结果; 1,3,7,4,8,7,5,1 1,3,7,4,8,7,5,1

I need to use those ID numbers to add the RETAIL_PRICE of each item together. 我需要使用这些ID号将每个项目的RETAIL_PRICE加在一起。 I've tried the following but it didn't allow for the item ID to be used more than once so it only added the RETAIL_PRICE from 1,3,7,4,8,5 which leaves out the values from the other 7 and 1. I need to add them with those 2 values included. 我尝试了以下操作,但不允许多次使用项目ID,因此仅从1,3,7,4,8,5添加了RETAIL_PRICE,而从其他7和1.我需要将它们添加为包含两个值。

SELECT SUM(RETAIL_PRICE) 
FROM `ITEMS` 
WHERE ID IN(1,3,7,4,8,7,5,1)

Thanks in advance. 提前致谢。

Assuming that id is the PRIMARY KEY (or a UNIQUE KEY) in ITEMS table, we can use a JOIN operation, to get all the rows that match, and the add up the retail price from each of the rows. 假设idITEMS表中的PRIMARY KEY(或UNIQUE KEY),我们可以使用JOIN操作来获取所有匹配的行,并从每行中加总零售价。

SELECT SUM(i.retail_price) AS tot_retail_price 
  FROM `ITEMS` i 
  JOIN `SALES` s
    ON s.item = i.id
 WHERE s.date        >= '2018-02-01'
   AND s.date        <  '2018-02-06'
   AND s.cash_credit =  '1'

As you observed, this condtion 如您所见,这种情况

WHERE ID IN (1,3,7,4,8,7,5,1)

is equivalent to 相当于

WHERE ID IN (1,3,4,5,7,8)

is equivalent to 相当于

WHERE ID IN (1,1,1,1,1,1,1,3,4,5,7,7,7,7,7,7,7,8)

That query is one pass through the table, evaluating each row in the table. 该查询是对表的一次遍历,评估表中的每一行。 It doesn't matter how many times a value is repeated in the IN list. 一个IN列表中的值重复多少次并不重要。 The condition is evaluated, and either a row satisfies the condition or it doesn't. 条件被评估,或者行满足条件或不满足。 The condition is TRUE or FALSE (or NULL). 条件为TRUE或FALSE(或NULL)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM