如何创建查询(计算列内的值)

时间:2016-03-09 08:49:20

标签: sql-server

我有3家公司1001,1002,1003它可能更多和11个容器有不同大小1,2,3,4,5我想要只返回公司中具有相同数量或更多的容器指定的数字。例如,如果我想要2个尺寸为1的集装箱和3个尺寸为2的集装箱,那么只有公司中具有2个或更多尺寸1和3或更大尺寸2的集装箱应该出现让我们说只有公司1001有他们然后它应该独自出现。 我尝试了不同的查询并发布了一个here,但他们建议我发布一个新问题,其中包含我要进行查询的问题。

(公司信息和容器信息分别在两个表中)

当我删除(基本上所有已选择的城市中的容器)

时,这就是我得到的
CoID    CoName          ContainerID   Price size1 size2  size3 size4 size5
6000001 hbjjvCompany    2000002       50    1     0      0     0     0
6000001 hbjjvCompany    2000003       50    1     0      0     0     0
6000002 NCompany        2000004       50    1     0      0     0     0
6000001 hbjjvCompany    2000005       100   0     1      0     0     0
6000002 NCompany        2000007       100   0     1      0     0     0
6000001 hbjjvCompany    2000008       200   0     0      1     0     0
6000001 hbjjvCompany    2000009       200   0     0      1     0     0
6000001 hbjjvCompany    2000010       200   0     0      1     0     0
6000002 NCompany        2000011       200   0     0      1     0     0
6000001 hbjjvCompany    2000012       400   0     0      0     0     1
6000003 ghhaCo          2000014       200   0     1      0     0     0

我应该得到什么

CoID    CoName                  size1 size2  size3 size4 size5
6000001 hbjjvCompany            2     1      3     0     1

当然我想要容器ID和价格,但我把它听起来像这样清楚我的查询显示所有容器,即使我删除了ContainerID和价格。

1 个答案:

答案 0 :(得分:0)

我认为你正在寻找:

CREATE TABLE #YourTable(CoID INT,CoName VARCHAR(100),ContainerID INT,Price DECIMAL(10,4),size1 INT,size2 INT,size3 INT,size4 INT,size5 INT);
INSERT INTO #YourTable VALUES
 (6000001,'hbjjvCompany',2000002,50,1,0,0,0,0)
,(6000001,'hbjjvCompany',2000003,50,1,0,0,0,0)
,(6000002,'NCompany',2000004,50,1,0,0,0,0)
,(6000001,'hbjjvCompany',2000005,100,0,1,0,0,0)
,(6000002,'NCompany',2000007,100,0,1,0,0,0)
,(6000001,'hbjjvCompany',2000008,200,0,0,1,0,0)
,(6000001,'hbjjvCompany',2000009,200,0,0,1,0,0)
,(6000001,'hbjjvCompany',2000010,200,0,0,1,0,0)
,(6000002,'NCompany',2000011,200,0,0,1,0,0)
,(6000001,'hbjjvCompany',2000012,400,0,0,0,0,1)
,(6000003,'ghhaCo',2000014,200,0,1,0,0,0);

SELECT CoID
      ,CoName
      ,SUM(Price) AS SumPrice
      ,SUM(size1) AS CountSize1
      ,SUM(size2) AS CountSize2
      ,SUM(size3) AS CountSize3
      ,SUM(size4) AS CountSize4
      ,SUM(size5) AS CountSize5
FROM #YourTable
GROUP BY CoID,CoName;

--Clean up
DROP TABLE #YourTable;

结果

CoID    CoName           SumPrice  s1  s2  s3  s4  s5
6000003 ghhaCo           200.0000   0   1   0   0   0
6000001 hbjjvCompany    1200.0000   2   1   3   0   1
6000002 NCompany         350.0000   1   1   1   0   0