簡體   English   中英

SQL count() where 匹配條件

[英]SQL count() where matches a criteria

我有以下數據。 有一個訂單 (1111) 有兩行相同的項目 (a),它們由類型“銷售”指示。

在此處輸入圖像描述

我有以下查詢來總結金額和稅款並計算數量如下

select 
  order_num
  , item_id
  , type
  , sum(amount) over (partition by order_num, item_id) as total_amount
  , sum(tax) over (partition by order_num, item_id) as tax
  , count (*) over (partition by order_num, item_id) as qty
from scratch.saqib_ali.temp_table
qualify  row_number() over(
  partition by order_num order by order_num)=1;

這會產生: 在此處輸入圖像描述

count(*) 只是計算行數。 我只想計算其中 type='sale' 的行。 我怎么做? 在這種情況下,數量應為 2。

我知道我可以使用 CTE 或子查詢來做到這一點,但是有沒有更優雅的方法來獲得這個?

你可以試試這個嗎?

select 
  order_num
  , item_id
  , type
  , sum(amount) over (partition by order_num, item_id) as total_amount
  , sum(tax) over (partition by order_num, item_id) as tax
  , sum (case when type='sale' then 1 else 0 end) over (partition by order_num, item_id) as qty
from scratch.saqib_ali.temp_table
qualify  row_number() over(
  partition by order_num order by order_num)=1;

這可能對你有用。

create or replace table order1 (order_num NUMBER(38,0), item_id varchar2(10), type varchar2(10), amount NUMBER(38,0), tax NUMBER(38,0));

insert into order1 values(1111,'a','sale',100,6);
insert into order1 values(1111,'a','discount',-10,0);
insert into order1 values(1111,'a','discount',-6,0);
insert into order1 values(1111,'a','sale',100,6);
insert into order1 values(1111,'a','discount',-5,0);
select * from order1;


select 
  order_num
  , item_id
  , type
  , sum(amount) over (partition by order_num, item_id) as total_amount
  , sum(tax) over (partition by order_num, item_id) as tax
  , count (*) over (partition by order_num, item_id) as qty
  , count_if (type='sale') over (partition by order_num, item_id) as qty
from order1
qualify  row_number() over(
  partition by order_num order by order_num)=1;

COUNT_IF的替代方法是:

COUNT(CASE WHEN type='sale' THEN type END) 
     OVER (PARITION BY by order_num, item_id) AS qty

如果類型不等於 'sale',則返回 case 表達式的默認NULL ,並且 NULL 值不計入COUNT function 中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM