SQL:如何将列值聚合并填充为新列

时间:2015-11-06 19:55:04

标签: sql sql-server

我有一个巨大的SQL,其结果类似于Table1。现在我需要将结果集作为Table2。这是来自SQL Server,但我们没有DB访问作为典型的方式,而是我们有一个内部工具,我们可以提交'选择' SQL语句,它将使用数据集转储excel文件。如何以table2格式获得结果?

注意:由于工具的性质,我们只能使用SQL命令,不能创建StoredProcedure,View等。

我们可以这样做吗?

SELECT 'Columns' From (Original SQL command) WHERE xxx GROUPBY YYY

表1

IDNameKey       |ID     |Name   |Location       |Type   |Active
================|=======|=======|===============|=======|=====
111             |11     |AAA    |LocA           |Type1  |No
222             |22     |BBB    |LocB           |Type2  |Yes
333             |33     |CCC    |LocA           |Type4  |No
444             |11     |AAA    |LocC           |Type2  |Yes
555             |55     |EEE    |LocB           |Type4  |No
666             |22     |BBB    |LocB           |Type2  |Yes

表2(预期方式)

ID      |Name   |Location |Type   |Active Count(Yes)  |Inactive Count(No)
========|=======|=========|=======|===================|=================
11      |AAA    |LocA     |Type1  |1                  |1
22      |BBB    |LocB     |Type2  |2                  |0
33      |CCC    |LocA     |Type4  |0                  |1
55      |EEE    |LocB     |Type4  |0                  |1

2 个答案:

答案 0 :(得分:1)

使用条件和

public ADALTokenCache(string signedInUserId)
{ 
    // associate the cache to the current user of the web app
    userId = signedInUserId;
    this.AfterAccess = AfterAccessNotification;
    this.BeforeAccess = BeforeAccessNotification;
    this.BeforeWrite = BeforeWriteNotification;
    // look up the entry in the database
    Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
    // place the entry in memory
    this.Deserialize((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits,"ADALCache"));
}

答案 1 :(得分:0)

对于初学者来说,给它一个旋转......

SELECT ID, Nave, Location, Type, 
   SUM(CASE Active WHEN 'Yes' THEN 1 WHEN 'No' THEN 0 END) as [Active Count(Yes)],
   SUM(CASE Active WHEN 'No' THEN 1 WHEN 'Yes' THEN 0 END) as [Inactive Count(No)]
FROM Table1
GROUP BY ID, Nave, Location, Type

有关CASE块的代码和图片密集型教程,请查看我的文章SQL Server CASE Solutions