[英]Not able to add row wise data in column form
EmpID (Primary Key) Sale Items Paid
ABC chair Yes
WXY chair Under Review
PER Laptop Yes
ABC Chair Yes
Now i want to create another table where i want to insert data Like below现在我想创建另一个表,我想在其中插入数据,如下所示
Emp ID Chair Laptop
ABC 2 0
WXY 1 0
My query to insert is我要插入的查询是
Select Emp Id from EMP,count(sales_item) as chair where Sales_Item = 'chair'
it is working now how to add Laptop (3rd Column ).现在正在工作如何添加笔记本电脑(第 3 列)。 can you please suggest
你能建议吗
You would use conditional aggregation:您将使用条件聚合:
Select EmpId,
sum(case when sales_item = 'chair' then 1 else 0 end) as chairs,
sum(case when sales_item = 'laptop' then 1 else 0 end) as laptops
from EMP
group by EmpId;
There is no reason to store this in a separate table.没有理由将其存储在单独的表中。 If you like, you can create a view.
如果你喜欢,你可以创建一个视图。 Then when you access the view, you know the data is up-to-date.
然后,当您访问视图时,您就知道数据是最新的。
You could use pivot for the expected result:您可以使用 pivot 获得预期结果:
DECLARE @t TABLE(
EmpID varchar(3)
,SaleItems varchar(10)
,Paid varchar(20)
)
INSERT INTO @t VALUES
('ABC', 'chair', 'Yes')
,('WXY', 'chair', 'Under Review')
,('PER', 'Laptop', 'Yes')
,('ABC', 'Chair', 'Yes')
SELECT piv.EmpID, ISNULL(piv.chair, 0) AS chair, ISNULL(piv.Laptop, 0) AS Laptop
FROM(
SELECT EmpID, SaleItems, 1 cnt
FROM @t
) x
PIVOT
(
SUM(cnt)
FOR SaleItems IN ([chair], [Laptop])
) piv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.