查找在日期 a 和 b 之间更改特定类型列的金额(int)的每个用户
Find every user that changed the amount(int) of a certain type column between dates a and b
我的 table 有 6 列,ID、用户名、地址、日期、类型和金额。
我想找到在日期 a 和 b 之间更改了特定类型列的数量 (int) 的每个用户。如果它是负数,我需要确切的差异,它必须显示负数。我面临的问题是数据库中没有唯一标识符(有些情况下除了数量之外的所有内容都是相同的)。 ID 没有用,因为它只是一个自动增量。
我写了这个声明:
SELECT a.Username, a.Address, a.diff, a.Type
FROM (
SELECT Username, Address, Type, MAX(Amount)-MIN(amount)AS diff
FROM dbo.data
WHERE Date='date1' OR Date='date2'
GROUP BY Username, Address, Type
HAVING MAX(amount) - MIN(amount) > 0
) a
ORDER BY diff;
这个语句的问题是:
- 这个差异只是正数并且
- 如果同一日期的同一用户使用相同类型的不同数量,它将输出该差异,我只想查看日期之间是否存在差异。
我知道这个数据库设计得很糟糕,但这家公司就是这样。感谢任何意见。
示例数据:
ID USERNAME ADDRESS TYPE AMOUNT DATE
0 JOHN street1 NKK 200 2022-05-22
1 ALEX street3 NKK 400 2022-05-22
2 MIKE street2 MKK 400 2022-05-22
3 MIKE street2 MKK 300 2022-05-22
4 MIKE street2 MLB 500 2022-05-22
5 JOHN street1 NKK 100 2022-05-23
6 ALEX street3 NKK 400 2022-05-23
7 MIKE street2 MKK 500 2022-05-23
8 MIKE street2 MKK 300 2022-05-23
9 MIKE street2 MLB 600 2022-05-23
输出:
USERNAME STREET TYPE DIFF
JOHN street1 NKK -100
MIKE street2 MKK 100
MIKE street2 MLB 100
我认为您只需要在两个日期内有条件地汇总:
with amounts as (
select *,
Sum(case when DATE='20220523' then AMOUNT end) over(partition by USERNAME,ADDRESS,TYPE)
- Sum(case when DATE='20220522' then AMOUNT end) over(partition by USERNAME,ADDRESS,TYPE) as Diff
from data
where DATE in ('20220522','20220523')
)
select distinct USERNAME, ADDRESS, TYPE, Diff
from amounts
where Diff != 0;
我的 table 有 6 列,ID、用户名、地址、日期、类型和金额。
我想找到在日期 a 和 b 之间更改了特定类型列的数量 (int) 的每个用户。如果它是负数,我需要确切的差异,它必须显示负数。我面临的问题是数据库中没有唯一标识符(有些情况下除了数量之外的所有内容都是相同的)。 ID 没有用,因为它只是一个自动增量。
我写了这个声明:
SELECT a.Username, a.Address, a.diff, a.Type
FROM (
SELECT Username, Address, Type, MAX(Amount)-MIN(amount)AS diff
FROM dbo.data
WHERE Date='date1' OR Date='date2'
GROUP BY Username, Address, Type
HAVING MAX(amount) - MIN(amount) > 0
) a
ORDER BY diff;
这个语句的问题是:
- 这个差异只是正数并且
- 如果同一日期的同一用户使用相同类型的不同数量,它将输出该差异,我只想查看日期之间是否存在差异。
我知道这个数据库设计得很糟糕,但这家公司就是这样。感谢任何意见。
示例数据:
ID USERNAME ADDRESS TYPE AMOUNT DATE
0 JOHN street1 NKK 200 2022-05-22
1 ALEX street3 NKK 400 2022-05-22
2 MIKE street2 MKK 400 2022-05-22
3 MIKE street2 MKK 300 2022-05-22
4 MIKE street2 MLB 500 2022-05-22
5 JOHN street1 NKK 100 2022-05-23
6 ALEX street3 NKK 400 2022-05-23
7 MIKE street2 MKK 500 2022-05-23
8 MIKE street2 MKK 300 2022-05-23
9 MIKE street2 MLB 600 2022-05-23
输出:
USERNAME STREET TYPE DIFF
JOHN street1 NKK -100
MIKE street2 MKK 100
MIKE street2 MLB 100
我认为您只需要在两个日期内有条件地汇总:
with amounts as (
select *,
Sum(case when DATE='20220523' then AMOUNT end) over(partition by USERNAME,ADDRESS,TYPE)
- Sum(case when DATE='20220522' then AMOUNT end) over(partition by USERNAME,ADDRESS,TYPE) as Diff
from data
where DATE in ('20220522','20220523')
)
select distinct USERNAME, ADDRESS, TYPE, Diff
from amounts
where Diff != 0;