Crosstab query :
A cross tab query is a transformation of rows of data to columns.It is easier review any data from rows.
Two examples of a cross-tab is to take the above data and show how much your shops stocked in each product across. This allows for easy comparison of stock by product.
This is source data from dbo.Shop's table.
Example 1 :
Move data in column of ProductNo to column of MLR,MLB and MLC.
SELECT ShopNo,
(SELECT Stock FROM dbo.Shop WHERE ShopNo = S.ShopNo AND ProductNo = 'MLR') AS MLR,
(SELECT Stock FROM dbo.Shop WHERE ShopNo = S.ShopNo AND ProductNo = 'MLB') AS MLB,
(SELECT Stock FROM dbo.Shop WHERE ShopNo = S.ShopNo AND ProductNo = 'MLC') AS MLC
FROM dbo.Shop S GROUP BY ShopNo
Result :
Example 2 :
This is example of summary stock by product.
SELECT ShopNo,
SUM(CASE WHEN ProductNo ='MLR' THEN Stock ELSE 0 END) AS MLR,
SUM(CASE WHEN ProductNo ='MLB' THEN Stock ELSE 0 END) AS MLB,
SUM(CASE WHEN ProductNo ='MLC' THEN Stock ELSE 0 END) AS MLC,
SUM(Stock) AS Total
FROM Shop
GROUP BY ShopNo
Result :
No comments:
Post a Comment