Sql&;计数

Sql&;计数,sql,count,distinct,Sql,Count,Distinct,下面是我的示例表“tbltemptransaction”和“tblProduct” 我现在可以在运行sql的地方得到userid=3的表,如下所示 pid pname description qty 1 HP PROBOOK 4440S Intel Core i5 5 1 HP PROBOOK 4440S Intel Core i5 3 6 DocuPrint C1110B 16ppm

下面是我的示例表“tbltemptransaction”和“tblProduct”

我现在可以在运行sql的地方得到userid=3的表,如下所示

   pid  pname                    description   qty
    1   HP PROBOOK 4440S    Intel Core i5   5
    1   HP PROBOOK 4440S    Intel Core i5   3
    6   DocuPrint C1110B    16ppm black 2
    2   iMac 21.5"          Intel Core i5   3
我可以知道如何编码,使它像下表吗

   pid  pname                    description    qty
    1   HP PROBOOK 4440S    Intel Core i5   8
    6   DocuPrint C1110B    16ppm black 2
    2   iMac 21.5"          Intel Core i5   3
如果pid相同,则数量将相加


谢谢。

pid
pname
description
相同时(如您的示例中所示),则
分组依据
将这些结果聚合到一行

select t.pid, t.pname, t.description, sum(t.qty) as qty
from tbltemptransaction t
group by t.pid, t.pname, t.description
编辑

select t.pid, sum(t.qty) as qty
from tbltemptransaction t
where pid = @userid
group by t.pid
select t.pid, p.pname, p.description, sum(t.qty) as qty
from tbltemptransaction t
inner join tblproducts p on p.pid = t.pid
where t.userid = 3
group by t.pid, p.pname, p.description
@用户id是会话的参数(“用户id”)

最终编辑

select t.pid, sum(t.qty) as qty
from tbltemptransaction t
where pid = @userid
group by t.pid
select t.pid, p.pname, p.description, sum(t.qty) as qty
from tbltemptransaction t
inner join tblproducts p on p.pid = t.pid
where t.userid = 3
group by t.pid, p.pname, p.description
试试看

Select distinct t1.pid,t1.name,t1.description,sum(t2.total2) From
(select pid,name,description,count(qty) as total1 from tbltemptransaction) as t1
left join (select COUNT(qty) as total2 from tbltemptransaction) as t2
on t1.pid=t2.pid
group by t1.pid,t1.name,t1.description

您好,谢谢您的回复。实际上,我的pname字段来自另一个表调用tblproducts。我可以知道如何从两个表中选择数据,其中pid=session(“userid”),如果pid等于数量之和。非常抱歉,我想我刚才问错了问题。实际上,我刚才显示的表数据基本上来自两个表tblproduct和tbltemptransition表。我需要的结果实际上是,如果userid=3,并且pid相同,那么相同产品的数量将相加。编辑问题如上图所示。感谢您从哪个表中获取
userid
?我将从会话中获取userid(“userid”),但对于此示例,我假设userid=3,我知道这一点,但在您的示例中没有列
userid
,如果我做了
pid=3
,那么您只会得到
NEC V260投影仪的结果
-这是您想要的吗?