在访问查询中计数(Distinct FieldName)

时间:2016-02-10 06:59:03

标签: sql sql-server ms-access

我正在尝试在Ms access 2010中编写一个查询,但它不允许使用Count(Distinct OrderID)语法,我很容易在oracle中编写。

Select BrandID, Count(Distinct OrderID), Count(Distinct ModelID)
 From ordertable
   Where Trunc(Pur_Date) Between '01-Feb-2015' And '09-Feb-2015'
Group By BrandID
Order by BrandID

表格结构:

 OrderID  BrandID  ModelID
   1        abc      a
   1        abc      b
   1        abc      c
   2        def      f
   3        ghi      a
   3        ghi      c
   4        abc      g
   4        abc      b

请帮助实现这一目标。

2 个答案:

答案 0 :(得分:0)

希望这会有所帮助..

 SELECT d.BrandID, Count(d.OrderID), Count(d.ModelID)
FROM (select distinct BrandID, OrderID,ModelID from ordertable
      Where Trunc(Pur_Date) Between '01-Feb-2015' And '09-Feb-2015') as d 
Group By d.BrandID
Order by d.BrandID

result

答案 1 :(得分:0)

根据How do I count unique items in field in Access query?访问权限没有COUNT DISTINCT运营商。解决方法是在子查询中SELECT DISTINCT并计算结果。此外,由于您要计算两个独立列,因此必须从两个单独的子查询计数 - 每列一个。最简单的方法是使用带有0占位符的UNION,然后对结果求和:

select BrandID, sum(orders), sum(models)
from (
    select BrandID, count(OrderID) orders, 0 models
    from (
        select distinct BrandID, OrderID
        from ordertable
        where Trunc(Pur_Date) between '01-Feb-2015' and '09-Feb-2015'
    ) x1
    group by BrandID
    union all
    select BrandID, 0 orders, count(ModelID) models
    from (
        select distinct BrandID, ModelID
        from ordertable
        where Trunc(Pur_Date) between '01-Feb-2015' and '09-Feb-2015'
    ) x2
    group by BrandID
) o
group by BrandID
在SQL Server中运行此查询的

Here's a SQL Fiddle demo

相关问题