存在的SQL

时间:2017-11-09 09:46:00

标签: mysql sql

我正在尝试获取在以下期间销售的特定产品的交易总支出。

    SELECT
  i.Customer,
  SUM(i.GrandTotal)
FROM
  transaction i
WHERE EXISTS
  (SELECT
    1
  FROM
    transactionline il
    INNER JOIN product p
      ON p.ProductId = il.ProductId
  WHERE i.InvoiceDate >= '2016-09-01 00:00:00'
    AND i.InvoiceDate <= '2017-08-31 23:59:59'
    AND p.TableProductType = 25)
GROUP BY i.Customer;

我的问题是,此查询的结果是在此期间花费的总金额,而不仅仅是涉及该产品的交易

我开始使用这样的东西:

SELECT
  i.Customer,
  SUM(i.GrandTotal)
FROM
  transaction i,transactionline il , product p
  WHERE i.InvoiceDate >= '2016-09-01 00:00:00'
    AND i.InvoiceDate <= '2017-08-31 23:59:59'
    AND p.TableProductType = 25);

但这也需要更长时间,最终结果是错误的(导致交易和交易行之间的连接引起的乘法)

1 个答案:

答案 0 :(得分:1)

几种方法,所有解决方案在查询之前直接使用with以下作为其数据源,但用您的表名替换

with dat
as
(
select 1 tranid,'N' Tableproducttype,9.00 GrandTotal   union all 
select 1,'N',11.12 union all
select 1,'N',14.23 union all
select 1,'25',8.88 union all
select 1,'N',7.77 union all
select 1,'Y',6.66 union all
select 2,'N',3.21 union all
select 2,'N',19.13 union all
select 2,'Y',1.23 union all
select 3,'Y',4.31 union all
select 4,'Y',15.43 union all 
select 4,'Y',15.12 union all
select 5,'N',14.32)

1。)使用IN

select tranid,sum(GrandTotal) GrandTotal
from dat
where tranid in (select tranid from dat where TableProductType = '25')
group by tranid

2。)使用存在

select tranid,sum(GrandTotal) GrandTotal
from dat
where exists (select 'x' from dat dat_inner 
              where dat_inner.TableProductType = '25' 
              and dat_inner.tranid = dat.tranid)
group by tranid

3。)使用,但可能很慢

select tranid,sum(GrandTotal) GrandTotal
from dat
group by tranid
having sum(case when TableProductType = '25' then 1 else 0 end)>0 /* at least one product of type 25 */