sql-server - SQL Server : trying to insert a count of zero when a record doesn't exist
问题描述
I am trying to modify the results of a query to populate a zero when a certain status doesn't exist.
In my base result I have something that looks like this:
But when a certain example doesn't appear in my table, I need a way to have a row show up with a zero for reporting needs, something like this:
I was trying to use a CTE maybe to populate those and left join it up...but doesn't seem to be working the way I want.
WITH DummyValues AS
(
SELECT 'Yellow' AS Val
UNION ALL
SELECT 'Red'
UNION ALL
SELECT 'Gray'
)
SELECT D.Val, V.PlntCd, COUNT(UpgradeMeasure)
FROM reporting.vw_SOTAgingView V
LEFT OUTER JOIN DummyValues D ON D.Val = V.UpgradeMeasure
GROUP BY D.Val, V.PlntCd
Is this an easy thing I am just missing something simple?
解决方案
你有向后的连接。
您离开了对子集的联接。(或者按照你拥有的方式和 RIGHT OUTER JOIN 进行操作,除非没有人真正使用右连接)
SELECT
*
FROM
TableWithAllData All
LEFT JOIN TableWithSomeData Some ON Some.Id = All.id
推荐阅读
- php - 不能从同一个类中定义的类函数调用函数
- powershell - PowerShell 上的 Send-MailMessage 不起作用
- c# - 如何保持或正确转换对象类型?
- php - PHP X-User 和 X-Password 身份验证
- vb.net - 相当于 DateTimePicker 上的 SelectionChangeCommitted?
- javascript - 通过 fb 登录网站时,我的函数 TestApi 不收集用户数据
- powershell - 使用 Powershell 将对象和字符串导出到 CSV
- javascript - 在增量中,为什么传递变量的值而不是值和增量?
- angular - 角材料:如何应用
标签上的消息 - windows - Mac 上的 git 将我未触及的文件视为已修改,并且它们也显示为已上演