2013-07-10 46 views
0

下面你好是我的示例表“tbltemptransaction” &“tblProduct”的Sql鲜明&计数

tbltemptransaction table  

userid pid pname description qty 
3 1 HP PROBOOK 4440S Intel Core i5 5 
3 1 HP PROBOOK 4440S Intel Core i5 3 
3 6 DocuPrint C1110B 16ppm black 2 
3 2 iMac 21.5"   Intel Core i5 3 
tblProduct table 

PID PName     Qty Description UnitPrice 
1 HP PROBOOK 4440S 20 Intel Core i5 2300 1  
2 iMac 21.5"   20 Intel Core i5 3999 2  
3 NEC V260 Projector 10 2700 lumens 2899 3  
4 DES-1228P Web Smart  10 24-Port  899 5  
5 DES-1210 Series   5 8-Port Web  699 5  
6 DocuPrint C1110B 15 16ppm black 899 4 

表其中userid = 3,我可以得到目前位置运行我的SQL是是这样。

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相同,那么qty会相加在一起。

谢谢。

回答

1

pid,pnamedescription是相同的(如在你的例子中),然后group by将聚合这些结果为一行。

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 

@user id是会话的参数( “用户id”)

最后编辑

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 
+0

嗨Gzaxx感谢您的回复。其实我的pname字段是从另一个表中调用tblproducts。我可以知道如何从pid = session(“userid”)的两个表中选择数据,并且如果pid等于数量的总和。 –

+0

看看我编辑的答案。 – gzaxx

+0

对于不满足感到非常抱歉,我想我刚才问了一个错误的问题。实际上,我刚才所展示的表格中的数据基本上来自两个表格产品和传感器表格。我需要的结果实际上是如果userid = 3和pid是相同的,那么相同产品的qty将相加在一起。编辑问题如上所示。感谢 –

0
select sum(qty) as qty, pid, pname, description from 
tbltemptransaction group by pid,pname, description 
0

试试看看

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