我有两个表,其结构如下:表A
itemId categoryId orderDate
==========================================
1 23 2016-11-08
1 23 2016-11-12
1 23 2016-11-16表B有结构
categoryId stock price
==========================================
23 500 600然而,我想要的输出应该像结果C一样
price stock orderdate qty
600 500 2016-11-08 (first order date) 3 (3 time appearance in first table)以下是我迄今所尝试过的
select b.price,b.stock from B b, A a
where b.categoryId = (
select a.categoryId
from A
GROUP BY categoryId
HAVING COUNT(categoryId)>1
)
and (a.orderdate = (
select MIN(orderdate)
from A
where categoryId = b.categoryId)
) 我有以下结果
price stock orderdate
600 500 2016-11-08 我不知道如何找到qty,因为它在第一个表中出现了3次。
发布于 2016-11-16 19:20:42
我认为您希望表a中的记录按项id和类别id分组,因此请将这两项按语句包含在组中。然后你必须用MIN,MAX,AVG,SUM等来聚合其他列。我使用MIN,它将给出这个特定列的组中最小的数字,尽管在这种情况下,使用MIN、MAX或AVG都不重要--这都是一样的。然后,COUNT(*)将只计算组中的整流杆数目。
而且,与带有逗号的列表表相比,联接通常是首选的。
SELECT a.itemid, a.categoryid, MIN(b.price), MIN(b.stock), min(a.orderdate), count(*) as qty
FROM a
INNER JOIN b ON a.categoryid = b.categoryid
GROUP BY a.itemid, a.categoryid发布于 2016-11-16 19:07:24
您还需要选择COUNT(*)
发布于 2016-11-16 19:22:08
使用以下sql如何?
select min(price), min(stock), min(orderDate), COUNT(categoryId)
from A,B where A.categoryId = B.categoryId
GROUP by A.categoryIdhttps://stackoverflow.com/questions/40640190
复制相似问题