gpt4 book ai didi

sql-server-2008 - SQL Server 2008 中多列中的 COUNT(DISTINCT)

转载 作者:行者123 更新时间:2023-12-05 01:23:19 25 4
gpt4 key购买 nike

在 Oracle 中,可以使用 获取多列中不同值的计数。 || 运算符(operator)(根据 this forum post ,无论如何):

SELECT COUNT(DISTINCT ColumnA || ColumnB) FROM MyTable

有没有办法在 SQL Server 2008 中做到这一点?我正在尝试执行单个查询以返回一些组统计信息,但我似乎无法做到。

例如,这是我要查询的值表:
AssetId MyId    TheirId   InStock
328 10 10 1
328 20 20 0
328 30 30 0
328 40 10 0
328 10 10 0
328 10 10 0
328 10 10 0
328 10 10 0

对于 AssetId #328,我想计算 中唯一 ID 的总数我的 ID 他们的 ID 列 (4 = 10, 20, 30, 40),以及 中非零行的总数有货 第 (1) 栏:
AssetId     TotalIds    AvailableIds
328 4 1

有没有办法以某种方式使用这种魔法?

最佳答案

您可以使用 cross applyvalues .

select T1.AssetId,
count(distinct T2.ID) TotalIds,
sum(case T2.InStock when 0 then 0 else 1 end) AvailableIds
from YourTable as T1
cross apply(values(T1.MyId, T1.InStock),
(T1.TheirId, 0)
) as T2(ID, InStock)
group by T1.AssetId
SE-Data
或者你可以做一个 union all在子查询中。
select T.AssetId,
count(distinct T.ID) TotalIds,
sum(case T.InStock when 0 then 0 else 1 end) AvailableIds
from (
select AssetId, MyId as ID, InStock
from YourTable
union all
select AssetID, TheirId, 0
from YourTable
) as T
group by T.AssetId

关于sql-server-2008 - SQL Server 2008 中多列中的 COUNT(DISTINCT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11920317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com