在MSSQL中计算列和行中的相同值

时间:2015-03-04 23:05:31

标签: sql-server count

Products               Orders
------------           ---------------------
PID | Name |            OID | pid1 | pid2 |
------------           ---------------------
1  | A100 |              1  |  2   |  1   |
2  | B100 |              2  |  3   |  1   |
3  | C100 |              3  |  2   |  2   |

 Output
----------
A100 | 2
B100 | 3
C100 | 1

我想在同一行和不同列中计算相同的产品。代码示例很棒。

感谢。

1 个答案:

答案 0 :(得分:0)

你可以做两个计数,然后对结果求和:

with cteOrderCount
AS
(
    select  p.Name as Name
            , count(o.OID) as orderCount
    from Products p
        inner join Orders o
            on p.pid = o.pid1
    group by p.Name
    union all
    select  p.Name
            , count(o.OID) as orderCount
    from Products p
        inner join Orders o
            on p.pid = o.pid2
    group by p.Name
)

select  Name
        , sum(OrderCount) as TotalOrders
from cteOrderCount
group by Name