Belki bir şey:
SELECT
SUM(t1.maxAmout)
FROM
(
SELECT
MAX(t.Amout) AS maxAmout,
t.Category
FROM
yourTable AS t
GROUP BY
t.Category
) AS t1
Böyle bunu da yapabilirsiniz. Eğer sql server 2005+ kullanıyorsanız:
SELECT
pvt.[1],
pvt.[2],
pvt.[3],
(
pvt.[1]+
pvt.[2]+
pvt.[3]
) AS Total
FROM
(
SELECT
t.Category,
t.Amout
FROM
yourTable AS t
) AS SourceTable
PIVOT
(
MAX(Amout)
FOR Category IN([1],[2],[3])
) AS pvt
DÜZENLEME
Eğer 1000 kategori var. Daha sonra dinamik bir pivot en iyi çözüm olacaktır. Böyle Yani:
Test verileri
CREATE TABLE #T
(
Category INT,
Amout FLOAT
)
INSERT INTO #T
VALUES
(1,4.6),
(1,4.6),
(1,4.6),
(2,5),
(3,4)
Benzersiz sütun adları
DECLARE @cols VARCHAR(MAX)
DECLARE @colsTotal VARCHAR(MAX)
;WITH CTE
AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY t.Category ORDER BY t.Amout) AS RowNbr,
t.*
FROM
#T AS t
)
SELECT @cols = COALESCE(@cols + ','+QUOTENAME(Category),
QUOTENAME(Category)),
@colsTotal=COALESCE(@colsTotal + '+ISNULL('+QUOTENAME(Category)+',0)',
'ISNULL('+QUOTENAME(Category)+',0)')
FROM
CTE
WHERE
CTE.RowNbr=1
ORDER BY
Category
Dinamik mil
DECLARE @query NVARCHAR(4000)=
N'SELECT
'[email protected]+',
(
'[email protected]+'
) AS Total
FROM
(
SELECT
t.Category,
t.Amout
FROM
#T AS t
) AS SourceTable
PIVOT
(
MAX(Amout)
FOR Category IN('[email protected]+')
) AS pvt'
EXECUTE(@query)
kullandığınız hangi sql sürümü? – Arion
Ben 2008 – richsoni