Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 重复值的运行计数_Sql Server_Powerbi_Dax - Fatal编程技术网

Sql server 重复值的运行计数

Sql server 重复值的运行计数,sql-server,powerbi,dax,Sql Server,Powerbi,Dax,我有一张表,显示托盘和托盘上的产品数量(“单位”)。由于多个可能的缺陷代码,单个托盘可能有多个记录。这意味着,当我试图合计所有托盘上的总单位时,同一托盘可能会被计数多次,这是不可取的。我想(但不知道如何)添加一个运行计数列,以显示特定托盘ID出现了多少次,以便我可以筛选出计数大于1的任何记录: | Pallet_ID | Units | Defect_Code | COUNT | +-----------+-------+-------------+-------+ | A1 |

我有一张表,显示托盘和托盘上的产品数量(“单位”)。由于多个可能的缺陷代码,单个托盘可能有多个记录。这意味着,当我试图合计所有托盘上的总单位时,同一托盘可能会被计数多次,这是不可取的。我想(但不知道如何)添加一个运行计数列,以显示特定托盘ID出现了多少次,以便我可以筛选出计数大于1的任何记录:

| Pallet_ID | Units | Defect_Code | COUNT |
+-----------+-------+-------------+-------+
| A1        | 100   | 03          | 1     |
| A1        | 100   | 05          | 2     |
| B1        | 95    | 03          | 1     |
| C1        | 300   | 05          | 1     |
| C1        | 300   | 06          | 2     |
| D1        | 210   | 03          | 1     |
| A1        | 100   | 10          | 3     |
| D1        | 210   | 03          | 2     |

在上述示例中,正确的单位总数应为705。SQL或DAX中的解决方案是可行的(尽管我倾向于SQL)。我已经搜索了很长时间,但找不到适合此特定场景的解决方案。非常感谢您的时间和考虑

您可以将窗口功能
行编号()
over
子句一起使用,在该子句中,您可以
按托盘划分。在每个分区中,您可以使用over子句中的
orderby
来控制将数字1分配给哪一行

select
*
from (
    select 
      Pallet_ID 
    , Units 
    , Defect_Code
    , row_number() over(partition by Pallet_ID order by defect_code) as count_of
    from yourtable
    ) 
where count_of = 1
注意,我可以使用列defect_代码进行排序,因为我不知道还有哪些列可能存在。如果您的表具有创建行的日期/时间值,则可以改用该值,也可以使用表的唯一键

旁注:
我不建议使用列别名“count”,因为它是SQL保留字

,所以您尝试了什么?你在哪里卡住了?请让我们看看你的尝试。