如何使用适当的密钥将表数据缩减到最小 - SQL?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用适当的密钥将表数据缩减到最小 - SQL?相关的知识,希望对你有一定的参考价值。
我正在使用MS SQL Server 2008,我有一个复杂的查询,它可以转动某些列以获得适当的数据报告。问题是,我正在使用连接和某些应该在同一个单元格中的单元格,如下图所示:
第19行和第20行应该是一行,绿色的单元格也应该在该行中,当然在适当的列中。
另外这是我的查询:
SELECT
Key1, Key2, Key3, Key4,
[1] AS 'Kolona1',
[2] AS 'Kolona2',
[3] AS 'Kolona3',
[4] AS 'Kolona4',
[5] AS 'Kolona5',
[6] AS 'Kolona6',
[7] AS 'Kolona7',
[8] AS 'Kolona8',
[9] AS 'Kolona9',
[10] AS 'Kolona10',
[11] AS 'Kolona11',
[12] AS 'Kolona12',
[13] AS 'Kolona13',
[14] AS 'Kolona14',
[15] AS 'Kolona15',
[16] AS 'Kolona16',
[17] AS 'Kolona17',
[18] AS 'Kolona18',
[19] AS 'Kolona19',
[20] AS 'Kolona20',
[21] AS 'Kolona21',
[22] AS 'Kolona22'
FROM
(SELECT
v.Key1, v.Key2, v.Key3, v.Key4,
v.Field1, r.Field2, v.Field3
FROM MYDB.dbo.MY_TABLE_1 AS v
INNER JOIN MYDB.dbo.MY_TABLE_2 AS r
ON r.Key1 = v.Key1) as [P]
PIVOT
(
Max (Field2)
FOR Field1 IN (
[1], [2],
[3], [4],
[5], [6],
[7], [8],
[9], [10],
[11], [12],
[13], [14],
[15], [16],
[17], [18],
[19], [20],
[21], [22])
) AS pvt
我应该在一行中显示前面相同4个键的所有日期。
答案
是的外部SELECT仍然是SELECT,因此您可以添加GROUP BY或其他随附的东西。因此,我设法通过将外部SELECT与我的自定义条件分组来获得我想要的东西。我设法用一些更通用的替换我自己的字段名称。这是代码:
SELECT
Key1, Key2,
Key3, Key4,
Key5, Key6,
Key7, Key8,
Key9, Key10,
Max([1]) AS 'controlCode1',
Max([2]) AS 'controlCode2',
Max([3]) AS 'controlCode3',
Max([4]) AS 'controlCode4',
Max([5]) AS 'controlCode5',
Max([6]) AS 'controlCode6',
Max([7]) AS 'controlCode7',
Max([8]) AS 'controlCode8',
Max([9]) AS 'controlCode9',
Max([10]) AS 'controlCode10',
Max([11]) AS 'controlCode11',
Max([12]) AS 'controlCode12',
Max([13]) AS 'controlCode13',
Max([14]) AS 'controlCode14',
Max([15]) AS 'controlCode15',
Max([16]) AS 'controlCode16',
Max([17]) AS 'controlCode17',
Max([18]) AS 'controlCode18',
Max([19]) AS 'controlCode19',
Max([20]) AS 'controlCode20',
Max([38]) AS 'controlCode21',
Max([39]) AS 'controlCode22'
FROM
(SELECT distinct
v.Key2, v.Key3,
v.Year, v.Key6 as Period,
k.Key1, k.Key4,
k.Key5, k.Key6,
v.controlCode, r.Name,
v.controlDate, v.Key7,
v.Key8, v.Key9,
v.Key10
FROM MyDB.dbo.VT_TABLE_1 AS v
INNER JOIN MyDB.dbo.KT_TABLE_2 as k
ON k.MyKey2 = v.Key2 AND k.MyKey1 = v.Key3
INNER JOIN MyDB.dbo.DATES AS r
ON r.controlCode = v.controlCode AND (v.controlCode < 21 OR v.controlCode > 37)
WHERE v.Year = Year
) as [P]
PIVOT
(
Max (controlDate)
FOR controlCode IN (
[1], [2],
[3], [4],
[5], [6],
[7], [8],
[9], [10],
[11], [12],
[13], [14],
[15], [16],
[17], [18],
[19], [20],
[38], [39])
) AS pvt
GROUP BY
Key1, Key2,
Key3, Key4,
Key5, Key6,
Key7, Key8,
Key9, Key10;
以上是关于如何使用适当的密钥将表数据缩减到最小 - SQL?的主要内容,如果未能解决你的问题,请参考以下文章
如何将表添加到 Windows Phone 上已部署的 SQL Server CE 数据库?
使用 Visual Studio 的新手,如何将表添加到数据库?