我有一张表,例如
Artist Title Song Key Easytosing
A Title A A No
A Title A B Yes
A Title A F Yes
B Title B A Yes
C Title C F# No
我想返回标记为“easytosing”的每首歌曲,但也会显示该歌曲的版本数量a)easytosing b)例如理想的结果将是:
Artist Title How_many_tot How_many_easy
A Title A 3 2
B Title B 1 1
我可以用以下方式展示有多少人很容易唱歌:
SELECT *, count(*) as How_many_easy from tracks
where easytosing='Yes'
group by artist,title
order by artist asc
有没有一种方法可以显示两者,所以查询只选择easytosing但是全部计算?
答案 0 :(得分:4)
select count(*) HOW_MANY_TOT,
sum(case EASYTOSING when 'Yes' then 1
else 0
end case) HOW_MANY_EASY
ARTIST,
TITLE
from TRACKS
group by ARTIST, TITLE
having HOW_MANY_EASY > 0
答案 1 :(得分:1)
我建议你做两个查询,一个用于数据,一个用于计数。您正在使用select *
,这意味着您正在选择整个表格,如果您只需要一个数字,这将有很多开销。
我已经建立了一个类似情况的网上商店,两个查询变得更快,分配更容易维护。只需选择1列并删除order by
即可优化计数。
另一种解决方案是使用count_value的子查询。子查询不支持限制,但您不需要计数。只需选择尽可能少的订单
答案 2 :(得分:1)
SELECT
Artist,
Title,
COUNT(*) How_many_tot,
SUM(Easytosing='yes') how_many_easy
FROM
tracks
GROUP BY
Artist, Title
HAVING
SUM(Easytosing='yes')>0
请参阅小提琴here。
答案 3 :(得分:0)
您是否尝试过将其作为子查询并添加where子句?
SELECT countTable.*,
count(*) as How_many_easy
FROM
(
SELECT Artist,
Title,
MAX(easytosing) as easytosing,
count(*) as How_many_total
from tracks
group by artist,title
) countTable ON tracks.Artist
where easytosing='Yes'
group by artist,title
order by artist asc
注意:如果存在此类记录,则MAX(easytosing)应返回“Yes”,否则返回“No”。
答案 4 :(得分:0)
你必须在你的talbe中添加一个唯一的ID(auto_increment,在我的查询中它调用ID),然后你可以获得你想要的信息:
select tall.artist, tall.title, count(distinct tall.ID) as total, count(distinct teasy.ID) as easy from tracks as tall
left join tracks as teasy on teasy.artist=tall.artist and teasy.title=tall.title and teasy.easytosing='Yes'
group by tall.artist, tall.title