【发布时间】:2019-08-02 05:28:56
【问题描述】:
我是 SQL 新手,所以不太了解您是否可以帮助我消除查询 1 中的重复项或帮助我转置查询 2
旧查询 1:我已经尝试过以下查询,但返回了一些重复值:
select
ROW_NUMBER() OVER (ORDER BY count(case when TransactionType = 1 then 1 else null end) desc) AS 'td','',
Warehouse as 'td','',
Createdate as 'td','',
count(case when TransactionType = 1 then 1 else null end) as 'td','',
count(case when TransactionType = 5 then 1 else null end) as 'td','',
count(case when TransactionType = 6 then 1 else null end) as 'td','',
cast(round(sum(localamount),8) as decimal(18,2))as 'td',''
from
PaymentTrn (nolock)
where
CreateDate = cast(convert(varchar(8),getdate() -1,112) as int)
group by
Warehouse, CreateDate
order by
count(case when TransactionType = 1 then 1 else null end) desc
然后我尝试了计数(当 TransactionType = 1 然后 1 else null end 时的不同情况)但只给出 1。
对于查询 2(如下所示),在 DB invoice-type、transaction-type 和仓库中有 3 个(有用的)列,我需要从中获取数据。
重要提示:发票号码重复,所以我需要使用不同的
因为我得到了重复的值,所以我修改了查询,现在我需要将“无列名”列转换为行
查询的当前输出是:
warehouse no column name
1700 3
1700 6
1700 9
查询 2:
select warehouse,count(distinct(invoicenumber))
from PaymentTrn (nolock)
where CreateDate = cast(convert(varchar(8),getdate() -305,112) as int) and TransactionType = 1
group by Warehouse,CreateDate
union all
select warehouse,count(distinct(invoicenumber))
from PaymentTrn (nolock)
where CreateDate = cast(convert(varchar(8),getdate() -305,112) as int) and TransactionType = 5
group by Warehouse,CreateDate
union all
select warehouse,count(distinct(invoicenumber))
from PaymentTrn (nolock)
where CreateDate = cast(convert(varchar(8),getdate() -305,112) as int) and TransactionType = 6
group by Warehouse,CreateDate
预期的结果应该是:
warehouse transactiontype=1 transactiontype=5 transactiontype=6
1700 3 6 9
【问题讨论】:
标签: sql sql-server pivot distinct unpivot