我具有以下数据库架构:
商店 包含字段:ID,地址,名称
具有以下字段的产品: id,shop_id,类别(枚举:衣服,家具,电子产品)
有没有一种方法可以编写高效的查询来获取有关商店的信息,因此最终查询将生成有关每个商店的摘要。例如:
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
final String details = getItem(position);
ViewHolder viewHolder;
ViewHolder mainViewHolder = null;
if(convertView == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
viewHolder = new ViewHolder();
viewHolder.dealInfo = convertView.findViewById(R.id.dealinfo);
viewHolder.accept = convertView.findViewById(R.id.accept);
viewHolder.accept.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), details, Toast.LENGTH_SHORT).show();
}
});
convertView.setTag(viewHolder);
}
{
mainViewHolder = (ViewHolder) convertView.getTag();
mainViewHolder.dealInfo.setText(details);
}
return convertView;
}
答案 0 :(得分:1)
使用条件聚合:
select name, count(case when category='clothes' then 1 end) as clothes,
count(case when category='furniture' then 1 end) as furniture,
count(case when category='electronics' then 1 end) as electronic
from
(select name,category from shop inner join product
on shop.id=product.shop_id)a
group by name
答案 1 :(得分:1)
尝试使用Pivot
表。
枢轴:
PIVOT通过旋转唯一值来旋转表值表达式 从表达式的一列到输出的多列, 并在剩余的任何位置执行汇总 最终输出中所需的列值
取消枢纽:
UNPIVOT通过旋转列执行与PIVOT相反的操作 表值表达式转换为列值。
有关Pivot
的更多信息select *
from
(
select name, value
from(
select name, category
from test t
join shop s on s.id = t.shop_id) as s
unpivot
(
value
for col in (category)
) unp
) src
pivot
(
count(value)
for value in ([clothes], [furniture], [electronics])
) piv
答案 2 :(得分:0)
如果知道所需的列,我将其写为:
def example_delete_topics(a, topics):
""" delete topics """
# Call delete_topics to asynchronously delete topics, a future is returned.
# By default this operation on the broker returns immediately while
# topics are deleted in the background. But here we give it some time (30s)
# to propagate in the cluster before returning.
#
# Returns a dict of <topic,future>.
fs = a.delete_topics(topics, operation_timeout=30)
# Wait for operation to finish.
for topic, f in fs.items():
try:
f.result() # The result itself is None
print("Topic {} deleted".format(topic))
except Exception as e:
print("Failed to delete topic {}: {}".format(topic, e))
如果您不知道各列,还可以考虑使用select s.name,
sum( (p.category = 'clothes')::int ) as clothes,
sum( (p.category = 'furniture')::int ) as furniture,
sum( (p.category = 'electronic')::int ) as electronic
from shop s join
product p
on s.id = p.shop_id
group by s.name;
或动态SQL。