Mysql查询用于计算具有值的行数

时间:2015-06-03 10:53:37

标签: mysql

我有许多用户订购的库存清单。我需要知道有多少股票被标记为优先级=' Y'和' N'

SELECT
glidemedia.glide_outlet.run,
glidemedia.glide_stock.title,
glidemedia.glide_stock.stockID,
glidemedia.glide_stock.titleID,
glidemedia.glide_schedule_entry.priorityItem,
count(glidemedia.glide_schedule_entry.stockID) as stockCount,
count(glidemedia.glide_schedule_entry.priorityItem = 'Y') as priorityItemYes,
count(glidemedia.glide_schedule_entry.priorityItem = 'N') as priorityItemNo
FROM
glidemedia.glide_outlet
INNER JOIN glidemedia.glide_schedule_entry ON glidemedia.glide_outlet.outletID = glidemedia.glide_schedule_entry.outletID
INNER JOIN glidemedia.glide_stock ON glidemedia.glide_schedule_entry.stockID = glidemedia.glide_stock.stockID
WHERE
glidemedia.glide_outlet.run = 109
GROUP BY
glidemedia.glide_schedule_entry.stockID

1 个答案:

答案 0 :(得分:1)

更改

count(glidemedia.glide_schedule_entry.priorityItem = 'Y') as priorityItemYes,
count(glidemedia.glide_schedule_entry.priorityItem = 'N') as priorityItemNo

sum(glidemedia.glide_schedule_entry.priorityItem = 'Y') as priorityItemYes,
sum(glidemedia.glide_schedule_entry.priorityItem = 'N') as priorityItemNo

对于ANSI标准

sum( 
 case when glidemedia.glide_schedule_entry.priorityItem = 'Y' then 1 else 0 end
) as priorityItemYes

<强>更新 为什么sum()而不是count(),原因是您没有计算行数,而是计算使用某些条件出现某个列值的总和/次数。