我希望上周销售量排名前三的产品。
这是我的SQL查询。
select ProductId,sum(Quantity) as quantity,createdOn from
(SELECT inv.Id,invd.ProductId, invd.Quantity ,cast (inv.CreatedOn as date) as createdOn FROM Invoice as inv
INNER JOIN
InvoiceDetail invd
ON
invd.InvoiceId = inv.id
WHERE inv.CreatedOn >= DATEADD(day,-11117, GETDATE()) ) as tbl
group by createdOn , ProductId
ORDER BY createdOn DESC
但是我没有获得每个日期的前三名产品。如果我使用TOP 3,那么它只会给出前3种产品,而我希望上周每天都可以获得前3种产品。
答案 0 :(得分:3)
如果我理解正确,您可以将<div class="grid__item medium-up--one-fifth">
<span class="filter-label">Brands:</span>
{% assign tags = settings.brands_filter | escape | split: ',' %}
<select class="coll-filter">
<option value="" class="default-tag">All</option>
{% for tag in tags %}
{% if current_tags contains tag %}
<option value="{{ tag | handle }}" selected>{{ tag }}</option>
{% elsif collection.all_tags contains tag %}
<option value="{{ tag | handle }}">{{ tag }}</option>
{% endif %}
{% endfor %}
</select>
</div>
<script>
var allFilters = jQuery('.coll-filter, .coll-picker');
allFilters.change(function() {
var newTags = [];
jQuery('.coll-filter').each(function() {
if (jQuery(this).val()) {
newTags.push(jQuery(this).val());
}
});
if (newTags.length) {
var query = newTags.join('+');
if (jQuery('.coll-picker').length) {
window.location.href = '/collections/' + jQuery('.coll-picker').val() + '/' + query;
}
else {
window.location.href = jQuery('{{ '' | link_to_tag: '' }}').attr('href') + query;
}
}
else {
if (jQuery('.coll-picker').length) {
window.location.href = '/collections/' + jQuery('.coll-picker').val();
}
else {
{% if collection.handle %}
window.location.href = '/collections/{{ collection.handle }}';
{% elsif collection.products.first.type == collection.title %}
window.location.href = '{{ collection.title | url_for_type }}';
{% elsif collection.products.first.vendor == collection.title %}
window.location.href = '{{ collection.title | url_for_vendor }}';
{% endif %}
}
}
});
</script>
与windows function结合使用,以每天获得前三名Row_number
。
根据quantity
列从高到低的顺序,每天按createdon
行号。
quantity
[结果] :
;WITH CTE AS(
SELECT productid,quantity,createdon,Row_number() over(partition by createdon ORDER BY quantity DESC,productid DESC) as RN
FROM
(
SELECT invd.productid,
sum(invd.quantity) as quantity,
cast(inv.createdon AS date) AS createdon
FROM invoice AS inv INNER JOIN invoicedetail invd
ON invd.invoiceid = inv.id
WHERE inv.createdon >= dateadd(day,-11117, getdate())
GROUP BY cast(inv.createdon AS date), invd.productid
) AS tbl
)
SELECT *
FROM CTE
WHERE RN <= 3