在SQL Server中使用查询的表中的复选框类似功能

时间:2018-10-24 15:49:52

标签: sql sql-server sql-server-2008

我有一个主表,其中包含多个名称记录,但数量和颜色不同。

TblPrimary :当前表

id | name    | color | Quan  |
===+=========+=======+=======+
1  | Apple   | Red   | 10    |
2  | Banana  | Yellow| 5     |
3  | Mango   | Yellow| 8     |
4  | Apple   | Green | 20    |
5  | Banana  | Brown | 15    |
6  | Mango   | Orange| 12    |
7  | Mango   | Green |  5    |

这是我的主表,基本上我想要这样的主表中的数据。因此,基本上,主表中的Quan是主表中所有Quan的总和。主表中的颜色(红色,黄色,棕色);表示主表中水果是否存在该颜色的位。

TblMain :新的期望表

id | Name    | Quan  | Red | Yellow | Brown | Green | Orange |
===+=========+=======+=====+========+=======+=======+========+
1  | Apple   |  30   |  1  |   0    |  0    |   1   |  0     |
2  | Banana  |  20   |  0  |   1    |  1    |   0   |  0     |
3  | Mango   |  25   |  0  |   1    |  0    |   1   |  1     |

我有以下查询,并且有分组依据和总和。我无法填充主表的颜色部分。

INSERT INTO TblMain(Name, Quan)
    (SELECT Name, SUM(Quan)
     FROM TblPrimary
     GROUP BY Name)

2 个答案:

答案 0 :(得分:2)

您可以尝试在子查询中使用sum Windows函数,然后使用条件聚合函数获得预期的结果。

select  ROW_NUMBER() OVER(ORDER BY name) id,
        name,
    Quan, 
    SUM(CASE WHEN color = 'Red' THEN 1 ELSE 0 END) 'Red',
    SUM(CASE WHEN color = 'Yellow' THEN 1 ELSE 0 END) 'Yellow',
    SUM(CASE WHEN color = 'Brown' THEN 1 ELSE 0 END) 'Brown',
    SUM(CASE WHEN color = 'Green' THEN 1 ELSE 0 END) 'Green',
    SUM(CASE WHEN color = 'Orange' THEN 1 ELSE 0 END) 'Orange'
from (
    SELECT name,
    color,
    SUM(Quan) OVER(PARTITION BY name ORDER BY name) Quan  
    FROM TblPrimary
) t1
group by name,Quan  

sqlfiddle

结果

id  name    Quan    Red Yellow  Brown   Green   Orange
1   Apple   30      1   0       0       1       0
2   Banana  20      0   1       1       0       0
3   Mango   25      0   1       0       1       1

答案 1 :(得分:0)

您可以使用PIVOT将值转换为列。在您的情况下,这变得有些麻烦,因为您需要行总和以及0/1标志

SELECT
    name,
    ISNULL(Red,0) + ISNULL(Yellow,0) + ISNULL(Brown,0) + ISNULL(Green,0) + ISNULL(Orange,0) As Quan,
    CASE WHEN Red IS NULL THEN 0 ELSE 1 END AS Red,
    CASE WHEN Yellow IS NULL THEN 0 ELSE 1 END AS Yellow,
    CASE WHEN Brown IS NULL THEN 0 ELSE 1 END AS Brown,
    CASE WHEN Green IS NULL THEN 0 ELSE 1 END AS Green,
    CASE WHEN Orange IS NULL THEN 0 ELSE 1 END AS Orange
FROM  
  (SELECT name, color, Quan  
   FROM dbo.TblPrimary) AS SourceTable  
PIVOT  
(  
   SUM(Quan)
FOR color IN (Red, Yellow, Brown, Green, Orange)  
) AS PivotTable;  

如果直接显示颜色的总和而不是标志,则查询将简化为:

SELECT
    name, Red, Yellow, Brown, Green, Orange
FROM  
  (SELECT name, color, Quan  
   FROM dbo.TblPrimary) AS SourceTable  
PIVOT  
(  
   SUM(Quan)
FOR color IN (Red, Yellow, Brown, Green, Orange)  
) AS PivotTable;

结果将是:

name     Red  Yellow  Brown  Green  Orange
==========================================
Apple     10   null    null   20     null
Banana   null   5       15   null    null
Mango    null   8      null    5      12