我正在努力解决一个大问题并且无法看到它是如何完成的...所以任何帮助都会得到你们的赞赏SQL大师!
我现在拥有的是这样一张桌子:
Sticker Price Cash Price Credit Price Value
Yes Yes NULL 107
NULL Yes NULL 115
Yes Yes NULL 127
我需要做的是构建一个表(翻转)来显示:
Text Value IsDefault
Sticker Price Sticker 1
Cash Price Cash 0
并且不显示Credit Price,因为第一个表中的所有值都为NULL。
基本上我想只显示贴纸,如果它不是全部为NULL,如果它不是全部为现金,等等......
我想到了枢轴,但只是无法绕过它!
目前我有这个给出顶级表格:
SELECT SH1.[Sticker Price], SH1.[Credit Price], SH1.[Cash Price], SH1.[Credit Price], UG.Description as Value,
CASE ROW_NUMBER() OVER(ORDER BY UG.Description)
WHEN 1 THEN 1 ELSE 0 END as ISDEFAULT
FROM [uStore].[dbo].[ACL_UserGroup] UG
INNER JOIN [uStore].[dbo].[ACL_UserGroupMembership] UGM ON UG.UserGroupId = UGM.UserGroupId
INNER JOIN [XMPDBHDS].[XMPieHDSSchema60].[Sheet1] SH1 ON CONVERT(nvarchar(100), SH1.[Centre Code]) = UG.Description
WHERE UGM.UserId = 1012
我只是看不出如何通过我有限的SQL知识得到我想要的表...
答案 0 :(得分:0)
在这种情况下,您应该执行LEFT JOIN
而不是
SELECT SH1.[Sticker Price], SH1.[Credit Price],
SH1.[Cash Price],
SH1.[Credit Price],
UG.Description as Value,
CASE ROW_NUMBER() OVER(ORDER BY UG.Description) WHEN 1 THEN 1 ELSE 0
END as ISDEFAULT
FROM [uStore].[dbo].[ACL_UserGroup] UG
LEFT JOIN [uStore].[dbo].[ACL_UserGroupMembership] UGM
ON UG.UserGroupId = UGM.UserGroupId
LEFT JOIN [XMPDBHDS].[XMPieHDSSchema60].[Sheet1] SH1
ON CONVERT(nvarchar(100), SH1.[Centre Code]) = UG.Description
WHERE UGM.UserId = 1012
AND SH1.[Credit Price] IS NOT NULL
AND UGM.UserGroupId IS NOT NULL;
答案 1 :(得分:0)
最后,我使用了幸运枢纽:
SELECT DISTINCT [Text], SUBSTRING([Text], 1, CHARINDEX(' ', [Text])) as Value,
CASE ROW_NUMBER() OVER(ORDER BY [Text])
WHEN 1 THEN 1 ELSE 0 END as ISDEFAULT
FROM
( SELECT SH1.[Sticker Price], SH1.[Credit Price], SH1.[Cash Price], UG.Description
FROM [uStore].[dbo].[ACL_UserGroup] UG
INNER JOIN [uStore].[dbo].[ACL_UserGroupMembership] UGM ON UG.UserGroupId = UGM.UserGroupId
INNER JOIN [XMPDBHDS].[XMPieHDSSchema60].[Sheet1] SH1 ON CONVERT(nvarchar(100), SH1.[Centre Code]) = UG.Description
WHERE UGM.UserId = @UserID) U
UNPIVOT
(Details FOR [Text] IN ([Sticker Price], [Credit Price], [Cash Price] )
)AS unpvt group by [Text]
结果!!!