如何根据另一列获取计数器列?

时间:2018-02-06 17:01:33

标签: sql sql-server tsql

我有一张表格,其中包含有关建筑物的信息,有关费用的表格,有关用户的表格以及进行结算的表格。 在计费表中,我需要一个计数器来计算建筑物内的不同用户。 我尝试使用ROW_NUMBER()来做到这一点,但我无法获得所需的结果。

这是我目前的查询:

SELECT r.id, r.building_id AS zID,z.name AS zName,
r.user_id AS kID, k.Name AS kName,
expence_id AS uID,u.name AS uName,u.price AS uPrice,
IIF(u.unique=1,u.price,k.kvadratura * u.price) AS Balance,
r.year,r.month,
ROW_NUMBER() OVER(Partition by r.user_id ORDER BY r.id) AS Counter
FROM Bill r 
INNER JOIN Expences u ON r.usluga_id = u.id
INNER JOIN Building z ON r.zgrada_id = z.id
INNER JOIN User k ON r.korisnik_id = k.id
WHERE r.building_id =7

这是我的输出: enter image description here

我想要的是:

对于建筑物内的每个用户,计数器+ 1。

enter image description here

2 个答案:

答案 0 :(得分:2)

您应该使用/* * @param string $taxonomy The taxonomy name. */ add_action( 'registered_taxonomy', function ( $taxonomy ) { if ( 'my_taxonomy' === $taxonomy ) { global $wp_taxonomies; if ( ! is_array( $wp_taxonomies ) || ! isset( $wp_taxonomies[ $taxonomy ] ) ) { return; } $wp_taxonomies[ $taxonomy ]->show_ui = false; } } ); 代替DENSE_RANK

ROW_NUMBER

答案 1 :(得分:0)

尝试将expence_id添加到分区。

SELECT r.id, r.building_id AS zID,z.name AS zName,
r.user_id AS kID, k.Name AS kName,
expence_id AS uID,u.name AS uName,u.price AS uPrice,
IIF(u.unique=1,u.price,k.kvadratura * u.price) AS Balance,
r.year,r.month,
ROW_NUMBER() OVER(Partition by r.user_id, expence_id ORDER BY r.id) AS Counter
FROM Bill r 
INNER JOIN Expences u ON r.usluga_id = u.id
INNER JOIN Building z ON r.zgrada_id = z.id
INNER JOIN User k ON r.korisnik_id = k.id
WHERE r.building_id =7